Created
December 17, 2013 21:41
-
-
Save rodneyrehm/8013067 to your computer and use it in GitHub Desktop.
JavaScript - URL validation RegExp
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
// see http://rodneyrehm.de/t/url-regex.html#imme_emosol for the complete table | |
// expression by | |
var url_pattern = /^(https?|ftp|torrent|image|irc):\/\/(-\.)?([^\s\/?\.#-]+\.?)+(\/[^\s]*)?$/i; | |
var valid = [ | |
"http://foo.com/blah_blah", | |
"http://foo.com/blah_blah/", | |
"http://foo.com/blah_blah_(wikipedia)", | |
"http://foo.com/blah_blah_(wikipedia)_(again)", | |
"http://www.example.com/wpstyle/?p=364", | |
"https://www.example.com/foo/?bar=baz&inga=42&quux", | |
"http://✪df.ws/123", | |
"http://userid:[email protected]:8080", | |
"http://userid:[email protected]:8080/", | |
"http://[email protected]", | |
"http://[email protected]/", | |
"http://[email protected]:8080", | |
"http://[email protected]:8080/", | |
"http://userid:[email protected]", | |
"http://userid:[email protected]/", | |
"http://192.168.1.1/", | |
"http://192.168.1.1:8080/", | |
"http://➡.ws/䨹", | |
"http://⌘.ws", | |
"http://⌘.ws/", | |
"http://foo.com/blah_(wikipedia)#cite-1", | |
"http://foo.com/blah_(wikipedia)_blah#cite-1", | |
"http://foo.com/unicode_(✪)_in_parens", | |
"http://foo.com/(something)?after=parens", | |
"http://☺.damowmow.com/", | |
"http://code.example.com/events/#&product=browser", | |
"http://j.mp", | |
"ftp://foo.bar/baz", | |
"torrent://foo.bar/baz", | |
"image://foo.bar:993", | |
"irc://foo.bar:6667" | |
]; | |
var invalid = [ | |
"rdar://1234", | |
"http://", | |
"http://.", | |
"http://..", | |
"http://../", | |
"http://?", | |
"http://??", | |
"http://??/", | |
"http://#", | |
"http://##", | |
"http://##/", | |
"http://foo.bar?q=Spaces should be encoded", | |
"//", | |
"//a", | |
"///a", | |
"///", | |
"http:///a", | |
"foo.com", | |
"http://-a.b.co", | |
"http://a.b-.co" | |
]; | |
valid.forEach(function(text) { | |
if (!text.match(url_pattern)) { | |
console.error("failed to match", text); | |
} | |
}); | |
invalid.forEach(function(text) { | |
if (text.match(url_pattern)) { | |
console.error("failed to not match", text); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It doesn't work for:
https://off---white.com
which has several hyphens. such a weird URL.