Regular expression for URL validation (in JavaScript)
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
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.
Try this regex
/(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
It works best for me.
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