Created
January 13, 2019 03:41
-
-
Save jszym/3462c7cdaaf11b1ca255a88d084550de to your computer and use it in GitHub Desktop.
Function to validate URLs
This file contains 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 | |
------------------------------------------------------ | |
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