Last updated
What Is a Subdomain?
A subdomain is a prefix added to a domain name, separated by a dot.
For example, in api.example.com, api is the subdomain,
example is the second-level domain, and com is the TLD.
Subdomains are defined in DNS as separate A or CNAME records and can point to
different servers than the root domain.
Subdomain Naming Rules (RFC 1123)
| Rule | Valid | Invalid |
|---|---|---|
| Characters | a-z, 0-9, hyphen | underscore, space, special chars |
| Start/end | Letter or digit | Hyphen at start or end |
| Length per label | 1–63 characters | 64+ characters |
| Total hostname | Up to 253 characters | 254+ characters |
| Case | Case-insensitive | — |
Subdomain Validation in JavaScript
JavaScript
function validateSubdomain(subdomain) {
// Each label: 1-63 chars, alphanumeric + hyphen, no leading/trailing hyphen
const labelRegex = /^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/;
if (!subdomain) return { valid: false, reason: 'Empty subdomain' };
if (subdomain.length > 253) return { valid: false, reason: 'Too long (max 253 chars)' };
const labels = subdomain.split('.');
for (const label of labels) {
if (!label) return { valid: false, reason: 'Empty label (double dot)' };
if (label.length > 63) return { valid: false, reason: `Label too long: ${label}` };
if (!labelRegex.test(label)) return { valid: false, reason: `Invalid label: ${label}` };
}
return { valid: true };
}
validateSubdomain('api.v2.example.com'); // { valid: true }
validateSubdomain('-bad.example.com'); // { valid: false, reason: 'Invalid label: -bad' }