Hostname Validation With RFC 1123 Labels
Validate DNS hostnames label by label, enforcing length limits, allowed characters, hyphen placement and an optional root dot.
Code
export function isValidHostname(hostname) {
if (typeof hostname !== "string") throw new TypeError("hostname must be a string");
const value = hostname.endsWith(".") ? hostname.slice(0, -1) : hostname;
if (value.length === 0 || value.length > 253) return false;
return value.split(".").every((label) => {
if (label.length < 1 || label.length > 63) return false;
return /^[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/.test(label);
});
}How it works
Count the function isValidHostname as the entire surface area of Hostname Validation With RFC 1123 Labels.
TypeError is the guard’s signal — thrown at the branch, before any partial work happens.
What to watch for
- The guard
typeof hostname !== "string"short-circuits the flow with an earlythrowwhen its condition holds.
Applying it
Signature: export function isValidHostname(hostname)
The surface worth importing is isValidHostname; the helpers around it are private to the snippet.
Statements that matter
return value.split(".").every((label) => {
if (label.length < 1 || label.length > 63) return false;
return /^[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/.test(label);
});
if (typeof hostname !== "string") throw new TypeError("hostname must be a string");
if (value.length === 0 || value.length > 253) return false;
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.UUID Version DetectorValidate the 8-4-4-4-12 UUID layout and read its version (v1 to v8) and variant nibbles per RFC 9562, with full field decomposition.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.
FAQ
- How does the code behave when input is bad?
- The code refuses to continue: `TypeError` is thrown while the state is still recoverable.
- Do I need to install anything before running this?
- No — every API used here ships with the language runtime, so there is nothing to install. The file defines `isValidHostname` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.