Google Forms: How to Add Validated Fields for Precision with Apps Script
Check a Phone Number and Learn to Validate Form Fields
What is a Validated Field?
Definition: A field that has been checked to meet specific rules or criteria for correctness and formatting.
Purpose: Ensures the data entered is logical and adheres to predefined constraints or standards.
Examples:
An email field that checks for the presence of "@" and a domain structure (e.g.,
user@example.com
).A date field that ensures the value matches the format
YYYY-MM-DD
.A password field that enforces a minimum character length and complexity.
Key Characteristic: Validation checks are usually automated and occur at the point of data entry.
Google Apps Script on Google Forms
If you were not aware you can add a script to a Google Form like this:
Make a form
Do not make a field for the number, the script will do that
Find the three dots on the right side
Open the menu and select the Script Editor
Before making your next move, copy the Form Id from the url. It will look something like this after the /d/:
13YsDYLH_EC0lbeOM1u9m0aD53ZdGXXXXXXXXXXXX
The Code
This code uses a regular expression to check the number. The code ensures that the input is a 10-digit numeric string with no additional characters, spaces, or formatting.
You can go further by stipulating (), -, etc.
requireTextMatchesPattern('^\\d{10}$') // Only allows exactly 10 digits
Here is the full script:
function addPhoneNumberValidationToExistingForm() {
// Open the form by ID
const formId = "YOUR FORM ID"; // Your form ID
const form = FormApp.openById(formId);
// Add a question for the phone number
const phoneNumberItem = form.addTextItem();
phoneNumberItem.setTitle('Mobile Phone');
// Create a validation rule for 10-digit phone numbers
const phoneValidation = FormApp.createTextValidation()
.setHelpText('Enter a valid 10-digit phone number (numbers only, no dashes or spaces)')
.requireTextMatchesPattern('^\\d{10}$') // Only allows exactly 10 digits
.build();
// Apply the validation to the phone number item
phoneNumberItem.setValidation(phoneValidation);
Logger.log('Phone number validation for 10 digits added to the form.');
}
Once you save and run, the new field will appear.
The name of the field is set here:
phoneNumberItem.setTitle('Mobile Phone');
If you want to test and adjust, delete the field each time from the form.
Expand Your Thinking
Based on a variety of criteria from things like email messages, Google Drive data, Google Chat, etc. you could auto create forms for people to use to ensure they always have validation when working inside Google Workspace on your domain.
Futher, AI tools, like APIs from OpenAI and Athnropic, can be easily integrated into individual form fields (or the creation of fields).
If you start with validation of common fields, I promise you will start automating forms and data collection processes.