πŸ”Regex Recipes

Domain Name Validation

Validate domain names with support for subdomains and international domains (with punycode note).

Pattern

^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]$

Explanation

Validates domain names including subdomains. Labels can be 1-63 characters. Note: International domains must be punycode-encoded.

Examples

Simple domain
Input
example.com
Output
βœ“ Match
With subdomain
Input
mail.example.com
Output
βœ“ Match
Multiple subdomains
Input
api.staging.example.com
Output
βœ“ Match
Invalid - hyphen at start
Input
-example.com
Output
βœ— No match
Invalid - no TLD
Input
example
Output
βœ— No match

Code Examples

JavaScript
const domainRegex = /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]$/i;

// Validate domain
const isValid = domainRegex.test('example.com'.toLowerCase());

// For international domains, use punycode
const punycode = require('punycode/');
const encoded = punycode.toASCII('mΓΌnchen.de'); // 'xn--mnchen-3ya.de'

Try it Now

πŸ’‘ Tips

  • Convert to lowercase before validation
  • Use punycode library for international domains
  • Each label (part between dots) max 63 chars
  • Total domain name max 253 chars

⚠️ Common Pitfalls

  • International domain names (IDN) need punycode conversion
  • Does not validate if domain actually exists
  • TLD validation is basic (any 2+ letter combination)
  • Case-insensitive flag recommended