Hostname Validation With RFC 1123 Labels

Validate DNS hostnames label by label, enforcing length limits, allowed characters, hyphen placement and an optional root dot.

JavascriptForm Validation

Code

javascriptsnippet
9 lines
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 early throw when 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

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.