Regular expression for address field validation

What a regular expression can and cannot check in an address field, which characters break naive patterns, and when lighter validation or plain text is the safer choice.

A regular expression can check the shape of an address field. It cannot tell you whether the address exists, whether mail can be delivered there, or whether the person typing it actually lives there. This review covers where pattern validation helps, where it causes problems, what it changes about the data, and how copying, pasting and assistive technology affect the result.

Is regex validation suitable for an address field?

It is suitable only for narrow format checks on structured parts of an address. A five-digit US ZIP code with an optional four-digit extension follows a fixed shape, and a pattern can enforce that reliably. A two-letter state code also has a fixed shape, although a pattern alone accepts letter pairs that are not real states. For those cases, a list of allowed values works better than a pattern.

Pattern validation is a poor fit for free-form street lines, unit or apartment lines, and international addresses. Real addresses contain accented letters, apostrophes, hyphens, slashes, number signs, digits in unexpected places, and scripts other than Latin. A strict pattern on these lines rejects legitimate input. Rejected users then either abandon the form or alter their address until it passes, and an altered address is worse data than an unvalidated one.

The recommendation, then, is to use strict patterns for postal codes and fixed codes, use permissive checks on street lines (non-empty, a sensible maximum length, no control characters), and accept plain text with minimal validation when the form serves international users or when address quality matters more than format consistency. If you need to confirm that an address is deliverable, that requires an address verification service that checks against postal reference data. No regular expression can do that.

What a regular expression actually changes

A validation pattern changes nothing by itself. It tests whether the input matches and returns true or false. The stored characters stay exactly as typed. This matters because the word "validation" is often used loosely for two different steps: testing input, and cleaning it up before storage. Cleanup steps such as trimming whitespace, collapsing repeated spaces, replacing non-breaking spaces or applying Unicode normalization do alter the stored text, even when the text looks the same on screen.

Keep those steps separate in your code and be deliberate about which ones run before the pattern test. If you normalize first and validate second, you are validating the cleaned value, so that is the value you should store. If you validate the raw value but store a cleaned one, the check no longer describes what is in your database.

Example patterns

The following JavaScript patterns illustrate the strict-versus-permissive split. They are starting points, not tested production rules.

const zipCode = /^\d{5}(?:-\d{4})?$/;
const stateCode = /^[A-Z]{2}$/;
const streetLine = /^[\p{L}\p{M}\p{N} .,'’#\/-]+$/u;

The ZIP pattern accepts five digits, optionally followed by a hyphen and four more digits. The state pattern only checks for two uppercase letters, so pair it with a list of valid codes. The street-line pattern uses Unicode property escapes: \p{L} for letters in any script, \p{M} for combining marks, and \p{N} for numbers. These escapes require the u flag in JavaScript. Without the flag, the pattern either fails to compile or does not mean what it appears to mean, depending on the engine and mode. The punctuation set is an assumption. Review it against the addresses your users actually enter rather than treating it as complete.

Preparing input before testing

function prepareAddressLine(raw) {
  return raw
    .normalize("NFC")
    .replace(/[\u00A0\u2007\u202F]/g, " ")
    .replace(/\s+/g, " ")
    .trim();
}

This function changes the stored characters. NFC normalization composes a base letter and a combining accent into a single precomposed character where one exists. Some sequences have no precomposed form, so the pattern still needs \p{M} to accept them. The replacement step converts common non-breaking and narrow spaces to ordinary spaces. The last two steps collapse runs of whitespace and remove leading and trailing spaces. Each of these steps is a policy decision. Document it so that whoever reads the stored data knows it is not a verbatim copy of the input.

Using the HTML pattern attribute

The pattern attribute on an input element is matched against the entire value, so anchors are implied. Current browsers compile it in a Unicode-aware mode, which is stricter about unescaped punctuation inside character classes. A pattern copied from server-side code can therefore behave differently or be ignored as invalid. Test the attribute in the browsers you support. Treat client-side checks as a convenience only, and repeat the validation on the server.

Characters that break naive patterns

Input feature | Why a simple pattern fails | Practical handling
Accented letters typed as base letter plus combining mark | An ASCII-only class such as [A-Za-z] rejects the combining mark | Normalize to NFC and include \p{M}
Letters outside the Latin alphabet | ASCII classes reject them entirely | Use \p{L} with the u flag, or skip character restrictions on street lines
Typographic apostrophe instead of the ASCII apostrophe | The pattern lists only one of the two characters | Allow both, or convert one to the other during preparation and document the change
Non-breaking or narrow spaces from pasted text | A literal space in a character class does not match them | Convert them to ordinary spaces before testing
Zero-width or bidirectional control characters | They are invisible but still count as characters | Reject or strip them deliberately, and tell the user if input was altered
Emoji | Usually not expected, and some are made of several code points | Decide explicitly whether to reject them; do not let a character count stand in for a length check

Will the address stay readable and usable after copying or sharing?

Address fields are frequently filled by pasting from email, documents, maps or password managers, and pasted text often carries characters the user cannot see. These include non-breaking spaces, trailing line breaks, typographic quotes and occasionally invisible formatting characters. A pattern that rejects these produces an error the user cannot diagnose, because the field looks correct. Normalizing these characters before testing, as in the preparation function above, avoids most of these failures. Telling users which character caused a rejection avoids the rest.

Validation does not change how an address reads when it is later copied out of your system, because the test leaves characters untouched. Cleanup steps can change it, though. Replacing typographic apostrophes, for example, alters the text that appears on labels, invoices and exports. Search and matching behave the same way: if one record was normalized and another was not, two visually identical addresses may fail to match. Apply the same preparation everywhere addresses are stored or compared.

Addresses written in right-to-left scripts, or mixing scripts with digits, can display in an unexpected order in some interfaces. Regex validation neither causes nor fixes this. If you strip bidirectional control characters for safety, check whether that changes how the stored address renders in the places it will be shown.

Accessibility of validation errors

The pattern itself is invisible to assistive technology. What users encounter is the error handling. Accessibility guidance such as WCAG calls for input errors to be identified and described in text, so a red border alone is not enough. Associate the error message with the field so screen readers announce it, state what is expected in plain language (for example, that a ZIP code needs five digits, optionally followed by a hyphen and four digits), and avoid messages that only say the format is invalid. Do not block typing or silently remove characters as the user types, because that confuses people using screen readers and voice input. How a specific screen reader announces your errors depends on your markup and should be checked with that screen reader rather than assumed.

Practical checklist

  • Use strict patterns only for fixed-format parts such as ZIP codes, and check state codes against a list.
  • Keep street and unit lines permissive: non-empty, a maximum length set by your storage and shipping requirements, and no control characters.
  • Separate testing from cleanup, and store the same value you validated.
  • Normalize Unicode and whitespace before testing so that pasted input does not fail invisibly.
  • Use Unicode property escapes with the u flag if you restrict characters at all.
  • Repeat client-side checks on the server.
  • Write error messages that explain the expected format in text and are programmatically tied to the field.
  • Use an address verification service, not a pattern, when deliverability matters.

Evidence gaps

No tool-specific documentation, test results or measurements were available for this review. The patterns and preparation steps above follow general, documented behavior of JavaScript regular expressions, Unicode normalization and HTML form validation. They were not tested against a specific browser, screen reader, address dataset or verification service. Before relying on them, test them against a representative sample of the addresses your users actually submit, and against the browsers and assistive technologies you support.