Does someone have a regex for validating urls (NOT for finding them inside a text passage)? JavaScript snippet would be preferred.
14 Answers
In the accepted answer bobince got it right: validating only the scheme name, ://, and spaces and double quotes is usually enough. Here is how the validation can be implemented in JavaScript:
var url = 'http://www.google.com';
var valid = /^(ftp|http|https):\/\/[^ "]+$/.test(url);
// true
or
var r = /^(ftp|http|https):\/\/[^ "]+$/;
r.test('http://www.goo le.com');
// false
or
var url = 'http:www.google.com';
var r = new RegExp(/^(ftp|http|https):\/\/[^ "]+$/);
r.test(url);
// false
References for syntax:
- 2,542
- 21
- 24
- 25,849
- 9
- 61
- 72
-
8@DerekHenderson Here you go, you W3Schools hater ;) – Akseli Palén Apr 29 '13 at 13:57
-
38+1 for getting an unnecessary -1 for W3Schools hate. – MaxArt Feb 12 '14 at 09:47
-
2This code won't work for many URLs. When detecting URLs, it's better to rely on a specialized library. [Here's why](http://stackoverflow.com/a/21925491/1269037). – Dan Dascalescu Feb 21 '14 at 06:19
-
var r = new RegExp(/^(ftp|http|https):\/\/[^ "]+$/); the parameter doesn't need '....' when new , just use /^(ftp|http|https):\/\/[^ "]+$/, as my try – Fanl Mar 31 '17 at 09:05
-
also +1 for getting an unnecessary -1 for W3Schools hate. – Yuriy Yakovenko May 05 '17 at 09:40
-
What does `[^ "]` mean in the regex? – sdfsdf Sep 15 '19 at 07:20
-
@MiLeung `[^ "]` means any character except a space or a double quote. – Akseli Palén Sep 16 '19 at 13:51
The actual URL syntax is pretty complicated and not easy to represent in regex. Most of the simple-looking regexes out there will give many false negatives as well as false positives. See for amusement these efforts but even the end result is not good.
Plus these days you would generally want to allow IRI as well as old-school URI, so we can link to valid addresses like:
http://en.wikipedia.org/wiki/Þ
http://例え.テスト/
I would go only for simple checks: does it start with a known-good method: name? Is it free of spaces and double-quotes? If so then hell, it's probably good enough.
-
3Ok. At least now I know it's probably not worth the effort in most cases :] Thanks. – Marek Stój Sep 11 '09 at 16:42
-
3
-
1Indeed, the right way to validate URLs is not to use a regular expression. Check out the [URI validation code in Node.js](https://github.com/joyent/node/blob/master/lib/url.js). It's far more complex than one regexp, which is why it's always better to use a specialized library rather than roll your own regular expression. – Dan Dascalescu Feb 21 '14 at 06:21
-
Two other things to consider: 1) tel:, mailto:, sms: are all valid hosts; 2) mobile browsers (especially iOS) allow other things instead of http/https/ftp for inter-app communication. – eliajf Apr 12 '16 at 00:09
Try this regex
/(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
It works best for me.
- 19,843
- 8
- 62
- 79
- 1,677
- 16
- 16
-
2
-
2This is not working for following urls : www.google.com , gogl.com , http://google.clo , www.google.co.in , www.goo.com.in.ssd – Jay Hardia Mar 10 '13 at 15:23
-
1This code won't work for many URLs. When detecting URLs, it's better to rely on a specialized library. [Here's why](http://stackoverflow.com/a/21925491/1269037). – Dan Dascalescu Feb 21 '14 at 06:19
I've found some success with this:
/^((ftp|http|https):\/\/)?www\.([A-z]+)\.([A-z]{2,})/
- It checks one or none of the following: ftp://, http://, or https://
- It requires www.
- It checks for any number of valid characters.
- Finally, it checks that it has a domain and that domain is at least 2 characters.
It's obviously not perfect but it handled my cases pretty well
- 154
- 2
- 4
This REGEX is a patch from @Aamir answer that worked for me
/((?:(?:http?|ftp)[s]*:\/\/)?[a-z0-9-%\/\&=?\.]+\.[a-z]{2,4}\/?([^\s<>\#%"\,\{\}\\|\\\^\[\]`]+)?)/gi
It matches these URL formats
- yourwebsite.com
- yourwebsite.com/4564564/546564/546564?=adsfasd
- www.yourwebsite.com
- http://yourwebsite.com
- https://yourwebsite.com
- ftp://www.yourwebsite.com
- ftp://yourwebsite.com
- http://yourwebsite.com/4564564/546564/546564?=adsfasd
- 3,831
- 1
- 13
- 34
- 54
- 1
- 5
<html>
<head>
<title>URL</title>
<script type="text/javascript">
function validate() {
var url = document.getElementById("url").value;
var pattern = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
if (pattern.test(url)) {
alert("Url is valid");
return true;
}
alert("Url is not valid!");
return false;
}
</script>
</head>
<body>
URL :
<input type="text" name="url" id="url" />
<input type="submit" value="Check" onclick="validate();" />
</body>
</html>
- 39
- 1
-
This code won't work for many URLs. When validating URLs, it's better to rely on a specialized library. [Here's why](http://stackoverflow.com/a/21925491/1269037). – Dan Dascalescu Feb 21 '14 at 06:19
-
Using pure JavaScript is better option of validations if you want to customize the pattern you can easily do that in your pattern – Swapnil Sep 24 '14 at 07:12
You can simple use type="url" in your input and the check it with checkValidity() in js
E.g:
your.html
<input id="foo" type="url">
your.js
$("#foo").on("keyup", function() {
if (this.checkValidity()) {
// The url is valid
} else {
// The url is invalid
}
});
- 647
- 5
- 15
-
BTW, I have realize that is worth notice that you should also do some kind of validation in the server side to avoid Injection attacks, as this solution is 100% client-side – Daniel Rodríguez Sep 29 '21 at 15:14
After a long research I build this reg expression. I hope it will help others too.......
url = 'https://google.co.in';
var re = /[a-z0-9-\.]+\.[a-z]{2,4}\/?([^\s<>\#%"\,\{\}\\|\\\^\[\]`]+)?$/;
if (!re.test(url)) {
alert("url error");
return false;
}else{
alert('success')
}
- 2,025
- 1
- 28
- 54
I couldn't find one that worked well for my needs. Written and post @ https://gist.github.com/geoffreyrobichaux/0a7774b424703b6c0fffad309ab0ad0a
function validURL(s) {
var regexp = /^(ftp|http|https|chrome|:\/\/|\.|@){2,}(localhost|\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|\S*:\w*@)*([a-zA-Z]|(\d{1,3}|\.){7}){1,}(\w|\.{2,}|\.[a-zA-Z]{2,3}|\/|\?|&|:\d|@|=|\/|\(.*\)|#|-|%)*$/gum
return regexp.test(s);
}
- 31
- 3
Try this regex, it works for me:
function isUrl(s) {
var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
return regexp.test(s);
}
- 22,497
- 8
- 84
- 119
- 45,173
- 14
- 109
- 137
-
1I'd like to be sure that I will not get false negatives with this regex. You had not problems with it? – Marek Stój Sep 11 '09 at 11:30
-
1No problems as of yet. Why not conduct tests on the false positives your anticipating? – ennuikiller Sep 11 '09 at 11:55
-
1It *would* give a false negative for symbols like ';' in the query, *except* that that's a great big `\S+` in the middle of the expression which can expand to match nearly anything, and it's not anchored at the end so you can put any trailing nonsense in. eg. ‘http://@’ or ‘http://I've got a lovely bunch of "coconuts"’ are ‘valid’. – bobince Sep 11 '09 at 11:55
I use the /^[a-z]+:[^:]+$/i regular expression for URL validation. See an example of my cross-browser InputKeyFilter code with URL validation.
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Input Key Filter Test</title>
<meta name="author" content="Andrej Hristoliubov anhr@mail.ru">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<!-- For compatibility of IE browser with audio element in the beep() function.
https://www.modern.ie/en-us/performance/how-to-use-x-ua-compatible -->
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<link rel="stylesheet" href="https://rawgit.com/anhr/InputKeyFilter/master/InputKeyFilter.css" type="text/css">
<script type="text/javascript" src="https://rawgit.com/anhr/InputKeyFilter/master/Common.js"></script>
<script type="text/javascript" src="https://rawgit.com/anhr/InputKeyFilter/master/InputKeyFilter.js"></script>
</head>
<body>
URL:
<input type="url" id="Url" value=":"/>
<script>
CreateUrlFilter("Url", function(event){//onChange event
inputKeyFilter.RemoveMyTooltip();
var elementNewInteger = document.getElementById("NewUrl");
elementNewInteger.innerHTML = this.value;
}
//onblur event. Use this function if you want set focus to the input element again if input value is NaN. (empty or invalid)
, function(event){ this.ikf.customFilter(this); }
);
</script>
New URL: <span id="NewUrl"></span>
</body>
</html>
Also see my page example of the input key filter.
- 609
- 4
- 12
-
-
h://google.com is valid URL. "h:" is valid prefix See https://www.w3.org/Addressing/URL/url-spec.txt for details. Examples of valid URL: mailto:myname@domain.com https://google.com If you want filter Hypertext Transfer Protocol only, you need use /^http:\/\/[^:]+$/i regular expression – Andrej Oct 08 '16 at 10:28
try with this:
var RegExp =/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/i;
- 768
- 11
- 15
/(?:http[s]?\/\/)?(?:[\w\-]+(?::[\w\-]+)?@)?(?:[\w\-]+\.)+(?:[a-z]{2,4})(?::[0-9]+)?(?:\/[\w\-\.%]+)*(?:\?(?:[\w\-\.%]+=[\w\-\.%!]+&?)+)?(#\w+\-\.%!)?/
- 187
- 4
-
I think your expression is missing a `:` between the protocol and `//`. Otherwise, it works fine! – Gustavo Straube Oct 18 '17 at 17:27