URL validation with Javascript

I am trying to use regex to validate user-entered URLs. I came up with this regex:

function is_valid_url(url)
{
     return url.match(/^(ht|f)tps?:\/\/[a-z0-9-\.]+\.[a-z]{2,4}\/?([^\s<>\#%"\,\{\}\\|\\\^\[\]`]+)?$/);
}

      

It works great for most simple urls. However, when I tried to enter this URL from Google Maps:

http://maps.google.com/maps?f=d&source=s_d&saddr=Brooklyn%2C+NY&daddr=Stewart+Ave&hl=en&geocode=FRBFbAId0JyX-ykJIXyUFkTCiTGGeAAEdFx2gg%3BFcAqbQIdgPuX-w&mra=mift&mrsp=1&sz=12&sll=40.65%2C-73.95&sspn=0.182857%2C0.308647&g=Brooklyn%2C+New+York%2C+NY%2C+United+States&ie=UTF8&z=12

      

The function then returns false even if that url is correct.

I know that using a regex to validate urls is controversial as there is no perfect solution for it, but I want to know if any regex that works better than mine works and can return true for such a url ...

0


source to share


2 answers


^((http|https|ftp):\/\/)?([a-z]+\.)?[a-z0-9-]+(\.[a-z]{1,4}){1,2}(/.*\?.*)?$

      

correspondences

http://www.example.com
www.example.com
example.com
example.info
abc.com.uk
www.example.co.in
www.example.com.sg
example.com.sg
t.com
co.co
https://www.t.co
asd.com.io/abc?foo=blah

      



False positives

abc.com.sg.in
example.com.aero.uk

      

+1


source


Easiest option: use a regex that works.

(((http|ftp|https):\/\/)|www\.)[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#!]*[\w\-\@?^=%&amp;/~\+#])?

      



Regexr: http://regexr.com?2tpo8

0


source







All Articles