You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Google Apps Script中用Regex验证Google表单文本响应?

Solution for Custom Regex Validation in Google Forms via Apps Script

I totally get where you're coming from—when first working with FormApp's validation methods, it's easy to miss the custom regex option since there are so many preset types. The good news is you absolutely can add custom regular expression validation using Apps Script, you just need to use the right method from the TextValidationBuilder class.

Here's a step-by-step example:

Let's say you want to add an email validation rule to a text input field. Here's how you'd do it:

function createFormWithRegexValidation() {
  // Create a new form (or use FormApp.openById("YOUR_FORM_ID") for an existing one)
  const form = FormApp.create("Customer Feedback Form");

  // Add a text input field for email
  const emailField = form.addTextItem();
  emailField.setTitle("Your Email Address");

  // Define your custom regex pattern (this one validates standard email formats)
  const emailRegex = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";

  // Build the validation rule
  const emailValidation = FormApp.createTextValidation()
    .requireTextMatchesPattern(emailRegex) // This is the key method for custom regex
    .setHelpText("Please enter a valid email (e.g., jane.doe@example.com)") // Error hint for users
    .build();

  // Apply the validation to the text field
  emailField.setValidation(emailValidation);
}

Key Notes:

  • The magic happens with requireTextMatchesPattern(regexString)—this method lets you pass any valid JavaScript regex pattern to validate user input.
  • Remember to escape backslashes in your regex (use \\ instead of \ since it's a string in JavaScript).
  • You can use this approach for any custom validation need: phone numbers, ZIP codes, special character requirements, etc.
  • For existing forms, just replace form.addTextItem() with form.getItemById("YOUR_ITEM_ID") (cast to a TextItem first) and apply the validation the same way.

The confusion often comes from mixing up FormApp.TextValidationBuilder with SpreadsheetApp.DataValidationBuilder—they're separate classes with different methods, but FormApp's builder absolutely supports custom regex via the method above.

内容的提问来源于stack exchange,提问作者Matthew

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:05:26