使用 Javascript 进行 URL 验证 [英] URL validation using Javascript

查看:28
本文介绍了使用 Javascript 进行 URL 验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用正则表达式来验证用户输入的 URL.我想出了这个正则表达式:

I'm 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<>\#%"\,\{\}\\|\\\^\[\]`]+)?$/);
}

它适用于大多数简单的 URL.但是,当我尝试从 Google 地图输入此 URL 时:

It works fine for most of the 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

然后函数返回 false,即使这个 URL 是正确的.

Then the function returns false, even though this URL is correct.

我知道使用正则表达式进行 URL 验证是有争议的,因为没有完美的解决方案,但我想知道您是否有任何比我的更有效的正则表达式,并且可以为那种 URL 返回 true.

I know using regex for URL validation is controversial as there's no perfect solution for it, but I want to know if you have any regex that works better than mine, and can return true for that kind of URL.

推荐答案

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

匹配

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

误报

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

这篇关于使用 Javascript 进行 URL 验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆