How to add validation to existing google form items via script?

怎甘沉沦 提交于 2019-12-06 14:42:22

问题


I am trying to add validation, specifically text validation, for my google form text items.

However, it looks to me like the 'setValidation()' function only works with items with known type like TextItem.

To my understanding, if I pull a form item via 'getItemById()', I would get a generic item. 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.

I have tried doing thing like .asTextItem() with no luck. Here is an example script that fails to run because of an error

'TypeError: Cannot find function setValidation in object Item. (line 10, file "Code")' on line 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


回答1:


You should add .build() at the end of your validation builder, as it's shown here.

Also, asTextItem should be called simultaneously with setValidation:

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);
  };
}


来源:https://stackoverflow.com/questions/47009462/how-to-add-validation-to-existing-google-form-items-via-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!