Sarit Rotshild
Sarit Rotshild

Reputation: 391

URL validation using Javascript doesn't work well

I use the following validation for url:

jQuery.validator.addMethod("urlValidatorJS", function (value, element) {
    var RegExp = (/^HTTP|HTTP|http(s)?:\/\/(www\.)?[A-Za-z0-9]+([\-\.]{1}[A-Za-z0-9]+)*\.[A-Za-z]{2,40}(:[0-9]{1,40})?(\/.*)?$/);
    return this.optional(element) || RegExp.test(value);
}, "The url is incorrect");

For some reason the following invalid url is valid according the validation above: http://www.example.com/ %20here.html (url with space).

How can I fix the validation?

Upvotes: 0

Views: 58

Answers (2)

Niklas
Niklas

Reputation: 375

At first: there already is a validation module from jQuery which you could use.

This would be your regex to match the URLs you mentioned (don't miss the i flag in the end!):

/^(https?:\/\/)(?:[A-Za-z0-9]+([\-\.][A-Za-z0-9]+)*\.)+[A-Za-z]{2,40}(:[1-9][0-9]{0,4})?(\/\S*)?/i

You were missing that there can also be other adresses like http://some.other.example.com. Also as mentioned in the other answer your identifier . was too greedy. I replaced it with \Sfor any non-whitespace character. You also had some unnecessary identifiers like {1} and your additional HTTP in the first part of your regex.

You can also use pages like regex101 to examine your regex and try it on different strings. It also explains each part of your regex so you can debug it better.

Upvotes: 1

Quentin
Quentin

Reputation: 943579

(\/.*)?

You said the (optional) last thing in the URL is a slash followed by any number of any character.

Be more specific than . if you don't want to allow spaces.

Upvotes: 1

Related Questions