如何在Google Apps Script中实现表单条件必填?setRequired()使用问题
Hey there! Let's break down why your current code isn't working and how to fix it to get that conditional required behavior you want.
What's Wrong With Your Current Code?
Your if (a != null) check doesn't actually look at the user's selection—it just confirms that the "cats/dogs" multiple-choice item was created successfully (which it always is). That's why the "Rate your interests" grid is always marked as required, no matter what the user picks.
To make a field required only when a specific choice is selected, we need to validate the user's submission after they fill out the form, or adjust the required status dynamically. The most straightforward method for Google Forms is using an installable submit trigger to enforce the rule.
Step 1: Update Your Form Creation Code
First, let's tweak the form creation script to track the IDs of the items we care about (we'll need these later for validation):
function createForm() { var form = FormApp.create('Pet Preference Form'); // Add condiment checkbox (keeping your original item) var condimentItem = form.addCheckboxItem(); condimentItem.setTitle('What condiments would you like on your hot dog?'); condimentItem.setChoices([ condimentItem.createChoice('Ketchup'), condimentItem.createChoice('Mustard'), condimentItem.createChoice('Relish') ]); // Add cat/dog choice item and save its ID var petChoiceItem = form.addMultipleChoiceItem() .setTitle('Do you prefer cats or dogs?') .setChoiceValues(['Cats','Dogs']) .showOtherOption(true); var petChoiceItemId = petChoiceItem.getId(); form.addPageBreakItem().setTitle('Getting to know you'); form.addDateItem().setTitle('When were you born?'); // Add interests grid and save its ID var interestsGridItem = form.addGridItem() .setTitle('Rate your interests') .setRows(['Cars', 'Computers', 'Celebrities']) .setColumns(['Boring', 'So-so', 'Interesting']); var interestsGridItemId = interestsGridItem.getId(); // Log URLs and item IDs (copy these IDs for the next step!) Logger.log('Published URL: ' + form.getPublishedUrl()); Logger.log('Editor URL: ' + form.getEditUrl()); Logger.log('Pet Choice Item ID: ' + petChoiceItemId); Logger.log('Interests Grid Item ID: ' + interestsGridItemId); }
Step 2: Create the Submission Validation Function
This function will check if the user chose "Cats" but skipped the interests grid, and block the submission if that's the case:
function validateFormSubmit(e) { var formResponse = e.response; var itemResponses = formResponse.getItemResponses(); var petChoice = null; var interestsFilled = false; // Loop through responses to find our target items for (var i = 0; i < itemResponses.length; i++) { var item = itemResponses[i]; var itemId = item.getItem().getId(); // Replace these with the IDs you copied from the Logger if (itemId == YOUR_PET_CHOICE_ITEM_ID) { petChoice = item.getResponse(); } else if (itemId == YOUR_INTERESTS_GRID_ITEM_ID) { interestsFilled = !!item.getResponse(); // Check if any option was selected } } // Block submission if user chose Cats but didn't fill the grid if (petChoice === 'Cats' && !interestsFilled) { throw new Error('Please rate your interests since you prefer cats!'); } }
Step 3: Set Up the Installable Trigger
To make the validation run when someone submits the form:
- In the Apps Script editor, go to Edit > Current project's triggers.
- Click Add trigger.
- Set these options:
- Choose function:
validateFormSubmit - Event source:
From form - Event type:
On form submit
- Choose function:
- Save the trigger (you'll need to authorize the script to access your form data).
How It Works
When a user submits the form, the validateFormSubmit function checks their response. If they selected "Cats" but left the interests grid blank, the submission is blocked, and they'll see your custom error message prompting them to fill the required field.
If you wanted to show the red "required" asterisk while the user is filling out the form, that's more complex (Google Forms doesn't support dynamic required status changes natively), but this submission validation method is reliable for enforcing your rule.
内容的提问来源于stack exchange,提问作者user9739730

