Regular expressions (regex) are a powerful tool for validating user input in web forms. When collecting addresses, you may want to ensure that the Address Line 1
and Address Line 2
fields do not contain unwanted characters, such as special symbols or emojis, and only allow valid address characters.
This article will show you how to use regex to validate these fields and provide some example patterns you can use or customize.
Why Validate Address Fields?
Prevent invalid or malicious input (e.g. emojis, or unsupported characters)
Ensure data consistency for shipping and billing
Improve user experience by catching errors early
Validation Rules Configuration
On the validation rules page at the bottom, you'll see these two options to configure regular expression validation. We've separated them out by Address Line 1 and Address Line 2 to give you the most flexibility.
To configure regular expressions, first write a warning message relevant to the rule you would like to make.
Using a website like regex101.com test your regular expression
Example, to validate that Address Line 2 does not have a period, you can use
\.
Common Requirements for Address Fields
Allow letters (A-Z, a-z)
Allow numbers (0-9)
Allow spaces
Allow common punctuation (commas, periods, hyphens, apostrophes, number signs)
Disallow special symbols (e.g.,
@
,!
,$
,%
,*
, etc.)Disallow emojis
Example Regex Patterns
1. Basic Address Line Validation
^[a-zA-Z0-9\s.,'#-]+$
Explanation:
^
and$
— Start and end of the string[a-zA-Z0-9\s.,'#-]
— Allow letters, numbers, spaces, periods, commas, apostrophes, number signs, and hyphens+
— One or more allowed characters
2. Disallowing Emojis and Special Symbols
If you want to be stricter and exclude all non-ASCII characters (including emojis):
^[a-zA-Z0-9\s.,'#-]{1,100}$
{1,100}
— Limits the length to 1–100 characters (adjust as needed)
Tips
Test your regex with various inputs to ensure it works as expected.
Adjust the pattern to fit your business rules (e.g., allow or disallow certain punctuation).
Combine with other validation (e.g., length checks, required fields).
Conclusion
Regular expressions are a flexible way to validate address fields and prevent unwanted characters. By customizing your regex patterns, you can ensure your address data is clean, consistent, and ready for processing.
Further Reading: