In Cognito Forms, you can validate user input in a variety of ways using the Textbox field. The Format Validation dropdown in the Textbox field settings gives you the option to validate data in both standard formats (Zip Code, SSN, etc.) and custom masks where users must enter numeric/alphabetic values in your own 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 users 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:
Have you written any awesome regular expressions that you’d like to share? Feel free to leave a comment down below!