Skip to main content

How to Add Data Validation in Forms with RegEx

You can validate user's answers in short text fields using regular expressions. For instance, if you want to set a condition where the user can only enter phone number in a specific format, RegEx can help.

To add validation to any Short Answer field, create the necessary RegEx and add it to the corresponding Validation field in the form designer.

RegEx

The regex [a-zA-Z0-9]10 will match any set of alpha numeric characters that are between 5 to 10 characters in length.

For exact matches, you can enclose the regular expression in the caret (^) and dollar sign ($) markers. A ^ matches the position at the beginning of the input string and a $ matches the position at the end of the string. If any characters are entered other than the required match, the input would be rejected.

Email Validation​

The RegEx for simple email validation is ^\S+@\S+\.\S+$ - it ensure that there are no spaces, there's one @ symbol and at least one space character.

Email Validation

Limit Length to 'n' Characters​

The RegEx [\w]{1,140} will not allow input longer than 140 characters in the text field.

ZIP Code​

The RegEx ^\d{5,6}(?:[-\s]\d{4})?$ will only accept valid US ZIP codes. Use [0-9]{4} for Austrian codes and [A-Za-z]{1,2}[0-9Rr][0-9A-Za-z]? [0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2} for UK postal codes.

Allow Alpha-numeric Characters​

The RegEx ^[A-Za-z0-9]{2}$ will only allow 2-character input containing alphabets or digits, no special characters are permitted.

ISBN​

The RegEx (?:(?=.{17}$)97[89][ -](?:[0-9]+[ -]){2}[0-9]+[ -][0-9]|97[89][0-9]{10}|(?=.{13}$)(?:[0-9]+[ -]){2}[0-9]+[ -][0-9Xx]|[0-9]{9}[0-9Xx]) validates both ISBN 10 and ISBN 13 formats.

^[A-Za-z0-9\s\-\’\.]{5,50}$ will match names having anywhere between 5 to 50 characters. These will however not work with non-English accented characters like Düsseldorf or Köln.

tip

You should learn regular expressions. They aren't just for programmers but can be useful for finding and replacing text in apps like Microsoft Word and Google Forms.