π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