Domain Name Validation Regular Expression

A valid domain name follows the rules defined in RFC 1035 and RFC 1123. Domain names consist of labels separated by dots, where each label can contain letters, numbers, and hyphens (but cannot start or end with a hyphen). The top-level domain (TLD) must be at least 2 characters long and consist of letters only. Domain names are used in email addresses, URLs, and other network identifiers.

Recommended Solution

^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$

Explanation

  • ^ - Start of the string.
  • (?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+ - One or more domain labels (e.g., "subdomain.example."):
    • [a-zA-Z0-9] - Must start with alphanumeric character.
    • [a-zA-Z0-9-]{0,61} - 0-61 characters of alphanumeric or hyphens.
    • [a-zA-Z0-9] - Must end with alphanumeric character (enforced when length > 1).
    • \. - Followed by a dot.
  • [a-zA-Z]{2,} - Top-level domain: at least 2 letters (e.g., com, org, museum).
  • $ - End of the string.

Notes

  • This regex validates the format of domain names but does NOT verify if a domain actually exists or is registered.
  • Each label can be up to 63 characters long, and the total domain name should not exceed 253 characters (not enforced by this regex).
  • This pattern supports internationalized domain names (IDN) in their ASCII-compatible encoding (Punycode) format (e.g., xn--80akhbyknj4f.com).
  • Trailing dots are not allowed in this pattern. If you need to accept FQDNs (Fully Qualified Domain Names) with trailing dots, modify the pattern to end with \\.?$.
  • Single-label domains (e.g., "localhost") are not accepted by this pattern as they lack a TLD.
  • For network identifiers, you may also need IP address validation as an alternative to domain names.

Implementation

const domainRegex = /^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/;
const isValidDomain = (domain) => domainRegex.test(domain);

Test Cases

Domain NameValid
example.com
subdomain.example.com
sub.domain.example.com
example.co.uk
my-site.com
example123.org
test.example.museum
a.b.c.d.example.com
xn--80akhbyknj4f.com
example
.example.com
example.com.
-example.com
example-.com
example..com
example .com
example.c
(empty string)
example.123
exam ple.com