如何判断单元格值是否已通过验证

kiw*_*ris 5 validation google-sheets google-apps-script

我熟悉 Google Apps 脚本DataValidation对象。获取和设置验证标准。但是如何以编程方式判断单元格值是否实际有效。因此,我可以在电子表格中看到红色的验证失败消息,但是可以通过代码获取单元格当前验证失败的事实吗?

我试图看看是否有一个单元格属性告诉你这一点,但没有。我还寻找了某种 DataValidation“验证”方法 - 即根据验证规则测试一个值,但也没有

有任何想法吗?这可能吗??

JSD*_*ton 6

具体回答您的问题,Google Apps 脚本中没有任何方法可以返回Range.isValid() 等的有效性。正如您所说,您可以使用然后解析其结果来对程序进行逆向工程Range.getDataValidations(),以便再次验证 a 的值Range.getValues()

这是一个很好的建议。我已向问题跟踪器添加了功能请求 ->添加星号以对其进行投票


小智 6

我为这个问题创建了一个解决方法,从技术上讲,它的工作方式非常丑陋,而且有点不确定。

关于解决方法: 它的工作原理是基于 Web 浏览器实现catch()函数允许访问 Google JS 代码部分抛出的错误的经验。如果单元格中的无效输入被验证规则拒绝,则系统将显示一条可由用户编写的 GAS 捕获的错误消息。为了使其首先工作,必须在指定的单元格上设置拒绝值,然后必须重新输入(修改)其值,然后 - 在此之后 - 调用内置函数getDataValidation()允许用户捕获必要的错误。使用此方法只能测试单个细胞,因为setCellValues()忽略任何数据验证限制(截至今天)。

缺点:

  • 此函数不一定会重新检查有效性:它会在将值插入单元格后立即调用单元格验证函数。因此该函数的结果可能是错误的。
  • 该代码会扰乱历史记录,因为单元格将被更改 - 如果它们有效的话。

我已经在 Firefox 和 Chromium 上成功测试了它。

function getCellValidity(cell) {
  var origValidRule = cell.getDataValidation();
  if (origValidRule == null || ! (cell.getNumRows() == cell.getNumColumns() == 1)) {
    return null;
  }
  var cell_value = cell.getValue();
  if (cell_value === '') return true; // empty cell is always valid
  var is_valid = true;
  var cell_formula = cell.getFormula();
  // Storing and checking if cell validation is set to allow invalid input with a warning or reject it
  var reject_invalid = ! origValidRule.getAllowInvalid();
  // If invalid value is allowed (just warning), then changing validation to reject it
  // IMPORTANT: this will not throw an error!
  if (! reject_invalid) {
    var rejectValidRule = origValidRule.copy().setAllowInvalid(false).build();
    cell.setDataValidation(rejectValidRule);
  }
  // Re-entering value or formula into the cell itself
  var cell_formula = cell.getFormula();
  if (cell_formula !== '') {
    cell.setFormula(cell_formula);
  } else {
    cell.setValue(cell_value);
  }
  try {
    var tempValidRule = cell.getDataValidation();
  } catch(e) {
    // Exception: The data that you entered in cell XY violates the data validation rules set on this cell.
    // where XY is the A1 style address of the cell
    is_valid = false;
  }
  // Restoring original rule
  if (rejectValidRule != null) {
    cell.setDataValidation(origValidRule.copy().setAllowInvalid(true).build());
  }
  return is_valid;
}
Run Code Online (Sandbox Code Playgroud)

我仍然建议给乔纳森打开的上述 Google 错误报告加注星标。