Validating DNS zone names (or more generally, fully qualified domain names - FQDNs) with a single, comprehensive regex is extremely challenging because of the various rules that involve both character patterns and length constraints (for individual labels and the total name).
While you can create a very long and complex regex that attempts to cover all rules, it often becomes unreadable, hard to maintain, and less efficient than a combination of a simpler regex and programmatic checks.
Let's break down the rules and then provide a robust approach.
DNS Domain Name Rules (RFCs 1035, 1123, 2181)
- Allowed Characters (LDH-rule):
- Letters:
a-z, A-Z (case-insensitive for resolution, but stored as-is).
- Digits:
0-9.
- Hyphen:
-.
- Label Structure:
- Labels are separated by dots (
.).
- Each label must start and end with a letter or digit.
- Hyphens are allowed in the middle of a label.
- Label Length:
- Each label must be between 1 and 63 characters long.
- Total Length:
- The total length of the FQDN (including dots) must not exceed 255 characters.
- The total length of the FQDN without the trailing dot (if present) must not exceed 253 characters. (e.g.,
example.com. is 12 chars, example.com is 11 chars). DNS resolvers strip the trailing dot for query purposes.
- Root Zone:
- The root zone is represented by a single dot (
.).
- No Consecutive Dots:
- No Leading/Trailing Dots (except for FQDN):
.example.com is invalid.
example.com. is a valid FQDN (explicitly terminates with root).
example.com is also valid (implies root).
Why a Single Regex is Hard
- Length constraints: Regex generally excels at pattern matching, not counting lengths between fixed delimiters. Enforcing "1 to 63 characters" and "total 255 characters" within a single regex is extremely verbose and can lead to performance issues.
- Contextual rules: "Starts/ends with alphanumeric" applies per label, which means the regex for the start of a label is different from its middle or end.
Recommended Approach: Regex + Programmatic Checks
This is the most common and robust way to validate DNS names.
1. The Regex (for character set and basic label structure)
This regex validates the allowed characters and ensures that labels don't start or end with hyphens. It also incorporates the 1-63 character length for each label, making it quite comprehensive for the individual label rules.
^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)*[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.?$|^(\.)$
Let's break it down:
^: Asserts the start of the string.
(?: ... ): Non-capturing group.
(\.): Special case for the root zone. Matches a single dot (.).
|: OR (allows either the root zone or a multi-label domain name).
(?: ... \.)*: Matches zero or more "label." patterns.
[a-zA-Z0-9]: A label must start with an alphanumeric character.
(?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?: This optional group handles the rest of the label:
[a-zA-Z0-9-]{0,61}: Allows 0 to 61 characters that are alphanumeric or hyphens in the middle.
[a-zA-Z0-9]: The label must end with an alphanumeric character.
- The
? makes this whole group optional, meaning a single-character label (e.g., a) is also valid.
\.: Matches the dot separator after a label.
[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?: This is the last label, which is not followed by a dot (unless it's the optional trailing dot). It uses the same label validation logic.
\.?: Allows an optional trailing dot, signifying an FQDN (e.g., example.com.).
$: Asserts the end of the string.
Example Use (Python):
import re
def is_valid_dns_name(name):
# Regex for character set, hyphen rules, and label length (1-63)
# This regex is case-insensitive, so re.IGNORECASE is not strictly needed for char matching,
# but good practice for ensuring DNS name handling.
# Note: this regex ensures labels are 1-63 characters, start/end alphanumeric, hyphens in middle.
# It also handles the root '.' and optional trailing dot.
dns_regex = r"^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)*[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.?$|^(\.)$"
# --- Step 1: Basic Regex Match ---
if not re.match(dns_regex, name, re.IGNORECASE):
return False, "Does not match basic DNS name pattern (invalid chars, hyphens, or label length)."
# --- Step 2: Total Length Check ---
# Total FQDN length (including dots, excluding potential final trailing dot)
# max 253 for resolution, max 255 for storage (including trailing dot).
# We'll check 255 as it's the maximum for the full string.
if len(name) > 255:
return False, "Total length exceeds 255 characters."
# --- Optional: Further programmatic checks for edge cases / redundancy ---
# The regex above already handles many, but explicitly splitting and checking can be clearer
# and catch unforeseen issues.
# If it's just the root domain, it's valid.
if name == ".":
return True, "Valid root domain."
# Remove trailing dot for label processing if present
processed_name = name.rstrip('.')
labels = processed_name.split('.')
# Check for empty labels (e.g. 'foo..bar' or '.foo')
if any(not label for label in labels):
return False, "Contains empty labels (e.g., consecutive dots or leading/trailing dot)."
# (This is largely covered by the regex, but good defensive programming)
return True, "Valid DNS name."
# --- Test Cases ---
valid_names = [
"example.com",
"www.example.com",
"sub-domain.example.com",
"a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p.q.r.s.t.u.v.w.x.y.z.aa.bb.cc.dd.ee.ff.gg.hh.ii.jj.kk.ll.mm.nn.oo.pp.qq.rr.ss.tt.uu.vv.ww.xx.yy.zz.example.com", # Long but valid
"123.example.com",
"xn--bcher-kva.example.com", # IDN (Punycode)
"example.com.", # FQDN with trailing dot
".", # Root domain
"a", # Single label domain
"longlabel" + ("a" * 58) # 63 chars long label
]
invalid_names = [
"-invalid.com", # Leading hyphen
"invalid-.com", # Trailing hyphen
"in--valid.com", # Consecutive hyphens are allowed within a label as per RFCs
"invalid..com", # Consecutive dots (empty label)
".invalid.com", # Leading dot
"invalid.com..", # Trailing dots (more than one)
"invalid,com", # Invalid character
"invalid_com", # Invalid character
"a" * 64 + ".com", # Label too long
"example." + ("a" * 250) + ".com", # Total length too long
"", # Empty string
" ", # Whitespace
"example.com ", # Trailing whitespace
" example.com", # Leading whitespace
]
print("--- Valid Names ---")
for name in valid_names:
is_valid, msg = is_valid_dns_name(name)
print(f"'{name}': {is_valid} - {msg}")
print("\n--- Invalid Names ---")
for name in invalid_names:
is_valid, msg = is_valid_dns_name(name)
print(f"'{name}': {is_valid} - {msg}")
Explanation of the Code and Approach:
- Regex First: The
dns_regex is designed to filter out the vast majority of invalid names related to character sets, hyphen placement within labels, and individual label lengths (1-63). It also correctly identifies the root . and handles optional trailing dots.
- Total Length Check: After the regex,
len(name) > 255 is a straightforward programmatic check that efficiently verifies the maximum allowed total length of the FQDN string. This is difficult to do reliably and readably purely in regex.
- Root Domain Handling: The regex already has a special case for
. (the root).
- No
split('.') and any(not label) for Length: While name.rstrip('.').split('.') is often used, the provided regex is already quite robust in preventing empty labels and enforcing label length. If the regex passes, an additional split and any(not label) check becomes somewhat redundant for this specific regex, as it inherently disallows empty labels and enforces the 1-63 length for each segment.
This combined approach provides both the pattern matching power of regex and the logical clarity of programmatic checks for constraints like total length.