Skip to content

Instantly share code, notes, and snippets.

@jszym
Created January 13, 2019 03:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jszym/3462c7cdaaf11b1ca255a88d084550de to your computer and use it in GitHub Desktop.
Save jszym/3462c7cdaaf11b1ca255a88d084550de to your computer and use it in GitHub Desktop.
Function to validate URLs
/**
VALIDATE URL
------------------------------------------------------
Requires punycode.js found at https://mths.be/punycode
to handle UTF-8. Has a very high true-positive rate,
and low false-positive rate on this test-suite
https://mathiasbynens.be/demo/url-regex
**/
function validate_url(link){
link = link.trim()
if (link.substring(0, 7) != "http://" && link.substring(0, 8) != "https://"){
link = "http://" + link
}
url = new URL(link);
link = url.protocol + "//" + punycode.toASCII(url.host + url.pathname + url.search)
var regexp = /^(?:http(?:s)?:\/\/)(?:(?:[\w:@_-]+\.)+[A-Za-z]+|(?:\d{1,3}\.){3}\d{1,3})(?::\d{1,4})?(?:[\/\w?#=&()_%-]+)?$/umi
if (regexp.test(link)) {
return link
}else{
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment