isValidZipCode
Validates if a string is a valid ZIP/postal code. Supports basic validation for US ZIP codes (5-digit or ZIP+4).
1/**
2 * Validates if a string is a valid ZIP/postal code.
3 * Supports basic validation for US ZIP codes (5-digit or ZIP+4).
4 *
5 * @param zip - The ZIP code string to validate.
6 * @returns True if the string is a valid ZIP code.
7 */
8export function isValidZipCode(zip: string): boolean {
9 return /^\d{5}(-\d{4})?$/.test(zip);
10}
Precise Pattern Matching
Uses a concise regular expression to validate both standard 5-digit and extended 9-digit ZIP+4 formats.
Zero-Dependency Implementation
Requires no external libraries or data sources, making it lightweight and easy to integrate.
Instant Performance
Executes in constant time with minimal processing overhead due to the simplicity of regex evaluation.
Safe and Robust Input Handling
Operates only on string input, reducing the risk of type errors or unexpected behavior.
Tests | Examples
1test('validates 5-digit ZIP code', () => {
2 expect(isValidZipCode('12345')).toBe(true);
3});
4
5test('validates ZIP+4 format', () => {
6 expect(isValidZipCode('12345-6789')).toBe(true);
7});
8
9test('invalid ZIP with letters', () => {
10 expect(isValidZipCode('12a45')).toBe(false);
11});
12
13test('invalid ZIP with too few digits', () => {
14 expect(isValidZipCode('1234')).toBe(false);
15});
16
17test('invalid ZIP+4 with missing dash', () => {
18 expect(isValidZipCode('123456789')).toBe(false);
19});
20
21test('invalid ZIP+4 with wrong digit count', () => {
22 expect(isValidZipCode('12345-678')).toBe(false);
23});
Common Use Cases
Form Field Validation
Validate shipping or billing ZIP code fields during checkout or registration flows.
API Input Validation
Ensure incoming user data includes properly formatted ZIP codes before further processing or storage.
Search Filters
Check if ZIP code filters in search or location queries are valid before applying them.
Data Cleansing
Validate and filter out improperly formatted ZIP codes in customer or address databases.