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
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