Skip to content

Instantly share code, notes, and snippets.

@eligrey
Last active March 21, 2023 23:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eligrey/6549ad0a635fa07749238911b42923da to your computer and use it in GitHub Desktop.
Save eligrey/6549ad0a635fa07749238911b42923da to your computer and use it in GitHub Desktop.
URL host validation utility
/**
* Validate URL host
*
* This supports domain names, IDN domain names, IPv4, and IPv6 addresses.
*
* Intentional spec incompatibilities:
* - Blank hosts ('') and blank FQDN hosts ('.') are considered invalid.
*
* @param host - Host to validate
* @returns true if host is valid and doesn't need additional encoding
*/
const isValidHost = (host: string): boolean => {
const url = new globalThis.URL('https://-');
url.host = host;
const parsed = url.host;
// If input host value is empty or contains [/\], or the processed
// host contains more '%' characters, then the input is an invalid
// or an improperly-encoded host.
return (
host.length > 0 &&
parsed.length > 0 &&
parsed.length >= host.length &&
// host does not include whitespace
!/\s/.test(host) &&
// host includes at least one 'letter' or 0-9 digit character
// (required reading: https://unicode.org/reports/tr18/#property_syntax )
/[\p{L}\p{Nd}]/u.test(host) &&
!/[/\\]/.test(host) &&
(host === '-' || parsed !== '-') &&
(parsed === host.toLowerCase() ||
(parsed.length > host.length &&
[...parsed.matchAll(/%/g)].length === [...host.matchAll(/%/g)].length))
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment