0

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?

2 Answers 2

1
(\/.*)?

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.

Sign up to request clarification or add additional context in comments.

5 Comments

@Quentin- so what exactly should I write in the Regex?
see my answer for that: use \S instead of . as your "any" character as it includes everything but whitespaces. Also you're missing some not too uncommon types of URLs such as http://some.other.example.com
@Niklas- so how can I not miss them?
@Niklas- the client validation of the js still doesn't work well....example.com %20here.html is still valid
using the regex I wrote in my answer example.com %20here.html does not match. I can't see where your mistake is.
1

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.

6 Comments

@Niklas- for what is the i in the end? I get error in the editor when I add it
the i is a regex flag to make everything case insensitive. I think you might have to delete your surrounding brackets so it will be var RegExp = / ... /i
@Niklas- I don't get the error in the js file. I get the error in groovy file: static constraints = { url (blank:false, matches: /^(https?:\/\/)(?:[A-Za-z0-9]+([\-\.][A-Za-z0-9]+)*\.)+[A-Za-z]{2,40}(:[1-9][0-9]{0,4})?(\/\S*)?/i) type (nullable:false) }
it seems like groovy has a different notation of regex flags: documentation
I write over the server validation which grails (groovy on rails) have
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.