Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression for URL validation (in JavaScript)

Does someone have a regex for validating urls (NOT for finding them inside a text passage)? JavaScript snippet would be preferred.

like image 470
Marek Stój Avatar asked Sep 11 '09 11:09

Marek Stój


People also ask

How do you check a URL is valid or not in JavaScript?

You can use the URLConstructor to check if a string is a valid URL. URLConstructor ( new URL(url) ) returns a newly created URL object defined by the URL parameters. A JavaScript TypeError exception is thrown if the given URL is not valid.

Which of the following regular expression is valid for validating the URL?

regex = “((http|https)://)(www.)? ”

What is a regular expression URL?

URL regular expressions can be used to verify if a string has a valid URL format as well as to extract an URL from a string.


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:

  • MDN RegExp Object
  • W3Schools RegExp Object
like image 57
Akseli Palén Avatar answered Oct 03 '22 11:10

Akseli Palén


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.

like image 37
bobince Avatar answered Oct 03 '22 12:10

bobince


Try this regex

/(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/

It works best for me.

like image 28
Musaddiq Khan Avatar answered Oct 03 '22 10:10

Musaddiq Khan


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

like image 35
Joey Avatar answered Oct 03 '22 12:10

Joey


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

  1. yourwebsite.com
  2. yourwebsite.com/4564564/546564/546564?=adsfasd
  3. www.yourwebsite.com
  4. http://yourwebsite.com
  5. https://yourwebsite.com
  6. ftp://www.yourwebsite.com
  7. ftp://yourwebsite.com
  8. http://yourwebsite.com/4564564/546564/546564?=adsfasd
like image 41
platonic Avatar answered Oct 03 '22 10:10

platonic


<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>
like image 35
Viet Nam Avatar answered Oct 03 '22 11:10

Viet Nam


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
    }
});
like image 43
Daniel Rodríguez Avatar answered Oct 03 '22 12:10

Daniel Rodríguez


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')
}
like image 28
Aamir Avatar answered Oct 03 '22 12:10

Aamir


Try this it works for me:

 /^(http[s]?:\/\/){0,1}(w{3,3}\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/;
like image 32
kalpana Avatar answered Oct 03 '22 10:10

kalpana


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);
}
like image 37
Geoffrey Avatar answered Oct 03 '22 10:10

Geoffrey


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);
}
like image 35
ennuikiller Avatar answered Oct 03 '22 11:10

ennuikiller


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;
like image 42
Amay Kulkarni Avatar answered Oct 03 '22 11:10

Amay Kulkarni


/(?:http[s]?\/\/)?(?:[\w\-]+(?::[\w\-]+)?@)?(?:[\w\-]+\.)+(?:[a-z]{2,4})(?::[0-9]+)?(?:\/[\w\-\.%]+)*(?:\?(?:[\w\-\.%]+=[\w\-\.%!]+&?)+)?(#\w+\-\.%!)?/
like image 44
Eru Avatar answered Oct 03 '22 12:10

Eru


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 [email protected]">
	<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.

like image 30
Andrej Avatar answered Oct 03 '22 11:10

Andrej