1

I have already found many posts on this subject, however no post handles my specific issue.

This is the regex that I use (found on this website) :

function validateUrl(value){ return /[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}([-a-zA-Z0-9@:%_\+.~#?&//=]*)/i.test(value); } 

This validates my url correct till up to the following point:

mydomain.tld/mypage/this'go(es{wro[ng

My function returns true, even when there are not-allowed characters like:
' or " or ( or ) or [ or ] or { or }

I don't understand why this is allowed. I have this: [-a-zA-Z0-9@:%_\+.~#?&//=]
Should return 'false' in my opinion...

3
  • I haven't looked at it closely, but my initial guess is that it's only matching a part of the input, but regex still considers a partial a match. To force it to check the whole input string, you need to use the ^ and $ anchors. Commented Jan 22, 2016 at 13:49
  • @StevenDoggart that sounds like an answer, doesn't it? Commented Jan 22, 2016 at 13:55
  • @Thomas True, but I didn't want to take the time to ensure that my hunch was correct. I'm happy enough to let Atif get the points if that really is the answer :) Commented Jan 22, 2016 at 13:56

2 Answers 2

2

Your regex almost works. In the string mydomain.tld/mypage/this'go(es{wro[ng it matches mydomain.tld/mypage/this. As you didn't put anchors in both ends, it does match (partially).

Just change it to:

^[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}([-a-zA-Z0-9@:%_\+.~#?&\/\/=]*)$ ^ ^ 

See LiveDemo

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

Comments

0

Please try this:

function validateUrl(value){ return /^(http(s)?:\/\/)?(www\.)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/.test(value); } 

1 Comment

Explaining why the original version doesn't work as expected would be great, so that the OP understands the issue.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.