Skip to content

Instantly share code, notes, and snippets.

@eugenemtn
Created June 20, 2021 00:29
Show Gist options
  • Save eugenemtn/9037e3a5d4fbd8f5e134bae8e674743d to your computer and use it in GitHub Desktop.
Save eugenemtn/9037e3a5d4fbd8f5e134bae8e674743d to your computer and use it in GitHub Desktop.
URL validator
function validURL(str) {
var pattern = new RegExp(
'^(https?:\\/\\/)?' + // protocol
'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // domain name
'((\\d{1,3}\\.){3}\\d{1,3}))' + // OR ip (v4) address
'(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*' + // port and path
'(\\?[;&a-z\\d%_.~+=-]*)?' + // query string
'(\\#[-a-z\\d_]*)?$',
'i',
); // fragment locator
return !!pattern.test(str);
}
function isValidHttpUrl(string) {
let url;
try {
url = new URL(string);
} catch (_) {
return false;
}
return url.protocol === 'http:' || url.protocol === 'https:';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment