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);
});
}Report a problem with this exampleOpens a pre-filled issue on GitHub.