Regular Expressions

Quick Tip

If you’re new to writing regular expressions, you can find a cheat sheet to review some basics here. Additionally, to test your expressions, RegExr is a great tool.

In Cognito Forms, you can validate user input in various ways using the Textbox field. The Format Validation dropdown in the Textbox field settings allows you to validate data in both standard formats (Zip Code, SSN, etc.) and custom masks where users must enter numeric/alphabetic values in a specified format. Plus, for our power users, we offer the ability to create regular expressions (regex for short), which allow you to validate or reformat very specific strings of text.

Depending on what you’re trying to accomplish, regular expressions can be quite tricky to write. While we don’t normally provide support for writing regular expressions, we would like to share some helpful expressions that our team (and our customers) have created!

Number Range

Collect numeric input within a specific range. For example, the expression below ensures that input must be numeric, exactly three digits, and in your specified range (ex: 002-899).

Regular Expression: ^([0-8])([0-9])([2-9])$

Make sure to include an error message. If the user enters the wrong number of digits or a number outside of the specified range, the error message will appear:

Hexadecimal Codes

Validate a hexadecimal code (ex: #FFF or #FF0000).

Regular Expression: ^([#]?)([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3}?)$
Reformat Expression: #$2

Make sure to include an error message. Now, when a user enters a hex code, the digits will be reformatted automatically to include a #:

If a user enters the wrong number of digits, they will see your error message.

Measurements

Height

Validate someone’s height (#’ ##").

Regular Expression: ^([0-9]?)([' ]?)([0-9]{1,2})([ "]?)$
Reformat Expression: $1'$3"
Make sure to include an error message. When the user enters their height, the digits will be reformatted with quotations separating feet from inches:

If the user enters more than three digits, the error message will appear.

Dimensions

You can also validate various individual measurements. To validate measurements in feet:

Regular Expression: ^([0-9]{1,2}?)([' ]?)$
Reformat Expression: $1'
Make sure to include an error message. If the user enters 1 or 2 digits, a single quote will automatically be added:

To validate measurements in inches, just change the single quote to a double quote.

Phone Numbers

While the Phone field already validates and reformats numbers into (xxx)-xxx-xxx, you may want to collect phone numbers in your own custom format. The method below will reformat the input into xxx-xxx-xxx if a user enters 10 digits or puts in a phone number with parentheses.

Regular Expression: ^(\()?([0-9]{3})[-\)]?([0-9]{3})[-]?([0-9]{4})$
Reformat Expression: $2-$3-$4
Make sure to include an error message. If the user enters 10 digits, the number will be reformatted with dashes:

Support