Reputation: 257
I am trying a regex to validate an Url.
var url = "https://www,google.com";
var urlRegex = /(https|http)?:\/\/(?:\w[\-\w.]+)(?:\/[\-\w+&@#\/%=~_|!:,.;]*)?(?:\?[\-A-Z0-9+&@#\/%=~_|!:,.;]*)?/i;
var result = urlRegex.test(url);
so i am getting "result" as true but i should get false as "url" contains comma. Kindly help.
Upvotes: 1
Views: 83
Reputation: 4887
You are getting true since your regex partly matches.
Use ^(https|http)?:\/\/(?:\w[\-\w.]+)(?:\/[\-\w+&@#\/%=~_|!:,.;]*)?(?:\?[\-A-Z0-9+&@#\/%=~_|!:,.;]*)?$
instead.
Upvotes: 2
Reputation: 626738
Add anchors (^
for beginning of a string, and $
for the end of the string):
^(https|http)?:\/\/(?:\w[\-\w.]+)(?:\/[\-\w+&@#\/%=~_|!:,.;]*)?(?:\?[\-A-Z0-9+&@#\/%=~_|!:,.;]*)?$
^ ^
See demo
Upvotes: 2