Help me validate url which should even accept .me domains
var tomatch= /http:\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/
if (tomatch.test(theurl))
{
window.alert("URL OK.");
return 开发者_高级运维true;
}
I tried this regular expression code to validate url .
When I try to validate it with http://about.me it showing error
Replace \.[A-Za-z]{3}
with \.[A-Za-z]{2,}
so it requires at least 2 TLD characters, but also allows more (there are e.g. .info
, .museum
, etc.!)
You also need to allow single-character domain names. Some registries allow them (DENIC/.de for example)!
Just change the {3} tp {2,3}
var tomatch= /http:\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{2,3}/
But do realise that Regex works this way:
http://test.meandmoretext
***************
The *'s mark where the RegEx has matched, so it returns "URL OK" even if you have much more text after the match. If you wanted a full-string match
var tomatch= /^http:\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{2,3}$/
But also realize that TLDs can go up to 6 characters.
Just to add to what others have already said:
Add ^
at the beginning and $
at the end or otherwise it will succeed even if it matches only part of your string – and if you're testing only part of your input then you're not doing proper validation.
Another thing would be to allow HTTPS URLs.
Also don't forget about the optional port.
And the path!
And a query string.
And a hash part.
Maybe you can get away without the basic auth user and password but technically it can be there.
Validating the URL is much harder than it may seem. I wouldn't even try to write the regex myself. Maybe try the Regex Library, search older questions here or Google: url validation javascript.
The last part of the regular expression [A-Za-z]{3}
means match all alphabets {3} means should have 3 chars.
change it to {2,}
精彩评论