← Resources RESOURCE
Practical tips and pitfalls for validating input like email, phone, and postal code with regex.

In form validation, regex works well for input with a regular format. To check that the entire string matches the format, you must pin both ends with ^ and $. Without anchors, a string passes even if only part of it matches, which breaks the validation. You can use the same regex directly in HTML's input pattern attribute.

For values with a fixed digit count and character type, like phone numbers, postal codes, and usernames, character classes and quantifiers alone are enough. However, if you narrow the rules too much, you'll block valid variations like international phone numbers, new postal code schemes, or the presence or absence of hyphens. Look at the diversity of real data first.

Don't try to perfectly validate email with regex. The official spec (RFC 5322) is so complex that it's hard to reproduce with a practical regex. Loosely check only that it contains an @ and a dot, and validate real deliverability by sending a confirmation email — that's the standard approach.

Browser-side regex validation is only for user convenience (UX), not a final line of defense. Always re-validate on the server, and watch out for catastrophic backtracking (ReDoS) with untrusted input (see the performance article in Resources).