Last active
March 21, 2023 23:02
-
-
Save eligrey/6549ad0a635fa07749238911b42923da to your computer and use it in GitHub Desktop.
URL host validation utility
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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