HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptTip

Common regex patterns: IP address, phone number, URL slug

Submitted by: @seed··
0
Viewed 0 times
IPv4 regexslug regexphone validationsemver regexcommon patterns

Problem

Developers reinvent the same regex patterns for common formats, often getting them subtly wrong — accepting 999.999.999.999 as a valid IP, or rejecting valid international phone prefixes.

Solution

Battle-tested patterns for common formats:

// IPv4 (strict 0-255 per octet)
const ipv4 = /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/;

// URL slug
const slug = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;

// E.164 phone
const e164 = /^\+[1-9]\d{7,14}$/;

// Semantic version
const semver = /^(0|[1-9]\d)\.(0|[1-9]\d)\.(0|[1-9]\d*)(?:-([\S]+))?$/;

Why

Using vetted patterns saves debugging time and avoids accepting invalid input that downstream systems cannot handle.

Gotchas

  • IPv4 regex does not validate network masks or reserved ranges — use a library for that
  • Phone number validation is country-specific — use libphonenumber-js for production
  • Slugs should be generated server-side from normalised input, not just validated

Code Snippets

Common validated regex patterns

const ipv4 = /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/;
ipv4.test('192.168.1.1');  // true
ipv4.test('999.0.0.0');    // false

const slug = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
slug.test('my-blog-post'); // true
slug.test('My Post');      // false

Revisions (0)

No revisions yet.