简体   繁体   English

如何通过脚本向现有的谷歌表单项添加验证?

[英]How to add validation to existing google form items via script?

I am trying to add validation, specifically text validation, for my google form text items.我正在尝试为我的 google 表单文本项添加验证,特别是文本验证。

However, it looks to me like the 'setValidation()' function only works with items with known type like TextItem .但是,在我看来, 'setValidation()'函数仅适用于具有已知类型的项目,例如TextItem

To my understanding, if I pull a form item via 'getItemById()' , I would get a generic item.据我了解,如果我通过'getItemById()'拉出一个表单项,我会得到一个通用项。 It still has 'TEXT' type but google script just doesn't see it as a TextItem and therefore the 'setValidation() ' function is not available for it.它仍然具有“TEXT”类型,但谷歌脚本只是没有将其视为 TextItem,因此'setValidation() setValidation 'setValidation() ”函数对它不可用。

I have tried doing thing like .asTextItem() with no luck.我试过做.asTextItem()类的事情,但没有运气。 Here is an example script that fails to run because of an error这是一个由于错误而无法运行的示例脚本

'TypeError: Cannot find function setValidation in object Item. 'TypeError: 在对象 Item 中找不到函数 setValidation。 (line 10, file "Code")' on line 9. (第 10 行,文件“代码”)'在第 9 行。

function validationTest() {
var form = FormApp.getActiveForm();
  var items = form.getItems();
  var textValidation = FormApp.createTextValidation()
    .requireNumberGreaterThanOrEqualTo(0)
    .requireWholeNumber();
  for (var i = 0; i<items.length; i++) {
    items[i].asTextItem();
    items[i].setValidation(textValidation);
  };
}

So, is there a known solution or workaround for this issue?那么,是否有针对此问题的已知解决方案或解决方法? Thank you in advance.先感谢您。

SC标准委员会

You should add .build() at the end of your validation builder, as it's shown here .您应该添加.build()在你确认生成器的结束,因为它显示在这里

Also, asTextItem should be called simultaneously with setValidation :此外,应与asTextItem同时setValidation asTextItem

function validationTest() {
var form = FormApp.getActiveForm();
  var items = form.getItems();
  var textValidation = FormApp.createTextValidation()
    .requireNumberGreaterThanOrEqualTo(0)
    .requireWholeNumber()
    .build();
  for (var i = 0; i<items.length; i++) {
    items[i].asTextItem().setValidation(textValidation);
  };
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM