US Address Validation Regex Guide (with Examples)

Author:

US Address Validation Regex Guide (with Examples): A Practical Guide for Developers

Introduction: The Checkout Error That Started It All

Imagine a developer named Michael who is preparing to launch an online store in the United States. The website is almost ready, the product pages look professional, and the payment system works as expected. Then a customer enters an address containing an apartment number, and the checkout form rejects it.

Michael investigates and discovers that his address validation rule is too restrictive. It accepts addresses such as 123 Main Street but rejects perfectly reasonable variations such as 123 Main St., Apt 4B.

He decides to solve the problem with a regular expression, commonly called a regex.

A regular expression is a pattern used to match or validate text. It can help developers check whether an address field follows an expected format before the information reaches a database or another service.

However, US address validation regex rules require careful planning. American addresses contain different street types, directional prefixes, apartment identifiers, and formatting variations. A pattern that looks correct in a simple example may reject valid addresses when real customers use it.

This guide explains how to build and test US address validation regex patterns, with practical examples in JavaScript and PHP. It also explains the limits of regex and shows when a more comprehensive address verification service is necessary.

What Is US Address Validation Regex?

US address validation regex is a regular expression designed to check whether address text follows a specified format.

For example, a developer might want to accept a street address such as:

123 Main Street

The application could also need to accept:

123 N. Main St., Apt 4B

Both examples contain a street number and street name, but the second includes a directional prefix, an abbreviated street type, punctuation, and an apartment identifier.

A regex can check for these expected elements. It can also reject entries that do not meet the application’s rules, such as an empty required field or a street address containing only punctuation.

The important distinction is that format validation is not the same as address verification.

A regular expression cannot establish that a street exists, that a building number is assigned to that street, or that a ZIP code corresponds to the city entered by the customer. It checks text against a pattern, not against authoritative postal records.

For that reason, developers should treat regex as one layer of address validation rather than a complete solution.

Why US Address Validation Matters

Michael initially believes that checking whether an address contains numbers and letters will be enough. After testing his checkout form, he discovers several problems.

Some customers use St. instead of Street. Others include apartment numbers, building identifiers, or directional prefixes such as N, S, E, and W. Some enter a street address on the first line and a unit number on the second.

A rigid regex can reject these legitimate variations, creating frustration and potentially preventing customers from completing purchases.

Address validation is important in several applications:

  • Ecommerce checkout forms that collect billing and shipping addresses.
  • Customer relationship management systems that store contact details.
  • Registration forms that require a US mailing address.
  • Delivery applications that collect destination information.
  • Databases that need consistent address formatting.
  • Automated software tests that check how applications handle different address inputs.

A good validation rule should reject clearly malformed data without making reasonable address formats unnecessarily difficult to enter.

Understanding the Structure of a US Street Address

Before writing a regex, Michael studies the fields he wants to validate.

A typical US mailing address can contain a primary address line, a secondary unit identifier, a city, a state abbreviation, and a ZIP code.

For example:

123 N Main St, Apt 4B
Springfield, IL 62704
United States

This example illustrates a familiar format. It should not be interpreted as proof that the particular street, city, and ZIP code combination identifies a deliverable address.

Each component has a different purpose.

The street number identifies a location along a street. The street name identifies the road, while a suffix such as Street, Road, or Avenue describes the street type. A directional prefix can distinguish one street segment from another.

Apartment, suite, and unit information identifies a secondary location within a building or property.

The city, state, and ZIP code provide additional geographic and postal information. These components should be validated separately when possible because each has its own rules.

This separation makes the code easier to maintain and helps avoid one oversized regex that attempts to validate every part of an address at once.

Building a Basic US Street Address Regex

Michael begins with a simple pattern that checks for a street number followed by a street name.

^\d+\s+[A-Za-z0-9.' -]+$

Here is what each component means:

  • ^ marks the beginning of the input.
  • \d+ matches one or more digits.
  • \s+ requires at least one whitespace character.
  • [A-Za-z0-9.' -]+ matches one or more letters, digits, spaces, periods, apostrophes, or hyphens.
  • $ marks the end of the input.

This pattern can accept examples such as 123 Main Street and 45 Oak-Ridge Road.

However, it is intentionally broad. It can also accept strings that look like an address but are not real or meaningful addresses.

It does not verify whether the street exists, and it does not understand the full range of US address formats.

That is why Michael treats it as a basic formatting check rather than a definitive validation rule.

Supporting Directional Prefixes and Street Suffixes

US street names can contain directional prefixes and suffixes. Examples include N, South, E, and West, as well as street types such as Street, Avenue, Boulevard, and Drive.

A developer may choose to use a more structured pattern for a controlled form:

^\d+[A-Za-z]?(?:\s+[NSEW]\.?)?(?:\s+[A-Za-z0-9.'-]+)+$

This pattern accepts a street number, an optional letter attached to that number, an optional single-letter directional prefix, and one or more words that form the street name.

Examples that fit the intended pattern include:

123 Main Street
45 N. Oak Avenue
12B West Lake Road

There is an important limitation. This pattern supports only a narrow set of directional formats. It does not fully support every written-out direction, compound street name, or special address convention.

For a production form, Michael decides not to rely on one street-line regex for every possible situation. He uses a reasonable baseline pattern and leaves room for additional address formats where necessary.

Validating Apartment, Suite, and Unit Numbers

Michael soon notices that apartment numbers create another challenge. Some customers enter Apt 4B, while others use Unit 12, Suite 300, or #7.

A separate regex can validate the secondary address field:

^(?:(?:Apt|Apartment|Unit|Suite|Ste|Floor|Fl|Room|Rm)\.?\s*)?[A-Za-z0-9-]+$

This pattern allows common unit designators followed by an identifier. However, because the designator is optional, it can also accept a standalone identifier such as 4B. If the application requires an explicit unit designator, the pattern should be adjusted accordingly.

Examples of intended inputs include:

Apt 4B
Unit 12
Suite 300
Floor 2

For optional fields, Michael allows the value to be empty and validates it only when the customer supplies information.

This distinction is important. A secondary address field should not become mandatory simply because the regex expects a unit number. Many residential addresses do not have apartments or suites.

Validating US State Abbreviations with Regex

The next step is validating state abbreviations.

A simple pattern can confirm that an input contains two uppercase letters:

^[A-Z]{2}$

This pattern accepts CA, TX, and NY. However, it also accepts invalid state codes such as ZZ.

For a more reliable check, Michael uses an explicit list of recognised state and District of Columbia abbreviations:

^(?:AL|AK|AZ|AR|CA|CO|CT|DE|FL|GA|HI|ID|IL|IN|IA|KS|KY|LA|ME|MD|MA|MI|MN|MS|MO|MT|NE|NV|NH|NJ|NM|NY|NC|ND|OH|OK|OR|PA|RI|SC|SD|TN|TX|UT|VT|VA|WA|WV|WI|WY|DC)$

This approach rejects two-letter combinations that are not in the list.

However, the application must decide how to handle US territories and other postal destinations. If the form supports them, their recognised abbreviations should be handled separately or added to the permitted set.

The state field should also be checked against the selected country. A state abbreviation alone does not establish that an address is located in the United States.

Validating US ZIP Codes with Regex

ZIP code validation is one of the simplest parts of US address form validation.

A standard five-digit ZIP code can be checked using:

^\d{5}$

For example, 62704 matches the pattern, while 6270 does not.

If the application accepts ZIP+4 formatting, use:

^\d{5}(?:-\d{4})?$

This allows a five-digit ZIP code with an optional hyphen and four additional digits.

Examples include:

62704
62704-1234

These patterns validate the structure of the ZIP code, not whether it has been assigned to a particular city or street.

Michael learns not to use a ZIP code regex as a substitute for postal verification. A five-digit number can match the pattern without corresponding to an assigned ZIP code.

For official postal addressing guidance, developers can consult USPS Publication 28, which describes address components, street suffixes, secondary unit designators, and other standardisation rules. <Cite refs={[“turn773142search1″,”turn773142search24”]}/>

United States Postal Service (USPS)

Headquarters: 475 L’Enfant Plaza SW, Washington, DC 20260, United States.

Official guidance: USPS Publication 28: Postal Addressing Standards.

Implementing US Address Validation in PHP

Michael now combines the individual patterns into a small PHP validation function.

PHP provides the preg_match() function for testing whether a string matches a regular expression. It returns 1 for a match, 0 for no match, and false if the matching operation fails. <Cite refs={[“turn773142search0”]}/>

PHP Group

Address: 2, Place de la Gare, L-1616 Luxembourg, Luxembourg.

Official documentation: PHP preg_match().

Here is a basic example:

<?php

function matchesPattern(
    string $value,
    string $pattern
): bool {
    return preg_match($pattern, $value) === 1;
}

$streetPattern =
    '/^\d+\s+[A-Za-z0-9.\x27 -]+$/';

$zipPattern =
    '/^\d{5}(?:-\d{4})?$/';

$statePattern =
    '/^(?:AL|AK|AZ|AR|CA|CO|CT|DE|FL|GA|HI|ID|IL|IN|IA|KS|KY|LA|ME|MD|MA|MI|MN|MS|MO|MT|NE|NV|NH|NJ|NM|NY|NC|ND|OH|OK|OR|PA|RI|SC|SD|TN|TX|UT|VT|VA|WA|WV|WI|WY|DC)$/';

$street = '123 Main Street';
$state = 'IL';
$zip = '62704';

$valid =
    matchesPattern($street, $streetPattern)
    && matchesPattern($state, $statePattern)
    && matchesPattern($zip, $zipPattern);

echo $valid
    ? 'Format checks passed'
    : 'Please review the address fields';

This example checks the three fields independently. It does not confirm that the address exists, and it does not validate the relationship between the street, city, state, and ZIP code.

For a production form, Michael would also trim unnecessary whitespace, handle empty required fields, set reasonable input-length limits, and return clear validation messages.

Implementing Address Validation in JavaScript

If the website needs to validate a field before submitting the form, JavaScript can provide immediate feedback.

For example:

const zipPattern = /^\d{5}(?:-\d{4})?$/;

function validateZipCode(value) {
    return zipPattern.test(value.trim());
}

console.log(validateZipCode("62704"));      // true
console.log(validateZipCode("62704-1234")); // true
console.log(validateZipCode("6270"));       // false

Client-side validation improves usability because customers can correct simple mistakes immediately.

However, JavaScript validation should not be the only protection. Users can bypass browser-side checks, so the server must repeat all important validation before saving or processing the information.

The client and server should also follow the same validation rules. Otherwise, an address might pass the browser check and fail after submission.

Common US Address Regex Mistakes to Avoid

As Michael expands his checkout system, he identifies several mistakes that developers should avoid.

Using one enormous regex for everything. Combining the street, apartment, city, state, and ZIP code into one pattern can make the rule difficult to understand and maintain. Separate field validation is usually easier to troubleshoot.

Assuming every street name uses the same format. Address lines may include hyphens, apostrophes, directional prefixes, building numbers, and other variations. A restrictive character class can reject legitimate inputs.

Confusing a valid format with a valid address. Regex cannot establish that a street exists or that a delivery provider serves a particular location.

Ignoring optional fields. Apartment numbers and secondary address lines should be optional unless the application has a specific reason to require them.

Rejecting useful punctuation. A blanket rule that permits only letters and digits may reject common address formatting. Decide which characters your application supports and test them deliberately.

Skipping server-side validation. Browser checks improve usability, but server-side validation remains necessary to protect the application’s data and processing logic.

When Should You Use an Address Verification API?

Regex is useful when the goal is to check basic input structure. It is not sufficient when a business needs to standardise addresses or confirm that a delivery destination is recognised.

For example, an ecommerce store may need to determine whether the city, state, and ZIP code correspond to a known postal record. A shipping operation may also need standardised address components to reduce delivery errors.

In these situations, an authoritative postal lookup or a suitable address verification service is more appropriate.

USPS Publication 28 provides guidance on standardised address formats and address components, while the USPS ZIP Code Lookup tool helps users find postal information. Developers should review the provider’s current requirements before integrating address verification into an application.

A sensible validation workflow therefore has three layers:

  1. Format validation: Use regex to check the structure of individual fields.
  2. Business-rule validation: Check that required fields are present and that combinations make sense for the selected country.
  3. Address verification: Consult an authoritative source when the application needs evidence that an address corresponds to a recognised postal destination.

These layers serve different purposes and work better together than a single complex regex.

Conclusion: Build Better Address Validation Without Rejecting Real Customers

A US address validation regex can help developers build more reliable forms, reduce simple input errors, and create consistent data for ecommerce applications, registration pages, and software testing.

Michael’s experience demonstrates why a single restrictive pattern is rarely enough. Street addresses, apartment numbers, state abbreviations, and ZIP codes each have different requirements. Validating them separately makes the rules easier to maintain and the results easier to explain.

The most effective approach is to use regex for what it does well: checking text against defined patterns. Use server-side validation for important application rules, and rely on an appropriate postal verification service when actual address validity matters.

By combining flexible patterns, clear error messages, and authoritative verification where necessary, developers can create address forms that are both dependable and user-friendly. The goal is not simply to reject incorrect entries. It is to help customers provide usable address information without unnecessary frustration.

Leave a Reply