简体   繁体   English

为什么此javascript网址验证程序失败?

[英]Why is this javascript url validator failing?

I have the following code to validate if a person entered a "valid" url in a textbox: 我有以下代码来验证是否有人在文本框中输入了“有效”网址:

 function validateURL(textval) {
var urlregex = new RegExp(
    "^(http:\/\/www.|https:\/\/www.|ftp:\/\/www.|www.){1}([0-9A-Za-z]+\.)");
return urlregex.test(textval);

} }

a user is getting an error where this is returning false for what seems like a valid urL 用户收到错误消息,错误消息中返回的错误值似乎是有效的urL

http://a.website.com/issues/i#browse/TEST-111

Can someone confirm why this example wouldn't pass the "valid url" test? 有人可以确认为什么此示例无法通过“有效网址”测试吗?

Can someone confirm why this example wouldn't pass the "valid url" test? 有人可以确认为什么此示例无法通过“有效网址”测试吗?

The main trouble with the regex is that www. 正则表达式的主要问题是www. part is obligatory in the pattern. 模式中必须包含部分。

If you want to make it optional, use a ? 如果要使其可选,请使用? modifier with a group around it ( (?:www\\.)? ): 修饰符周围有一个组( (?:www\\.)? ):

^(?:(?:(?:ftp|https?):\/\/)?)(?:www\.)?[0-9A-Za-z]+(?:\.[0-9A-Za-z]+)*

This will match http://a.website.com part. 这将与http://a.website.com部分匹配。 To match the whole string, you can use: 要匹配整个字符串,可以使用:

^(?:(?:(?:ftp|https?):\/\/)?)(www\.)?[0-9A-Za-z]+(?:\.[0-9A-Za-z]+)*(?:\/[^\/]*)*$

See demo 观看演示

 var re = /^(?:(?:(?:ftp|https?):\\/\\/)?)(www\\.)?[0-9A-Za-z]+(?:\\.[0-9A-Za-z]+)*(?:\\/[^\\/]*)*$/; var str = 'http://a.website.com/issues/i#browse/TEST-111'; if ((m = re.exec(str)) !== null) { document.getElementById("res").innerHTML = m[0]; } 
 <div id="res"/> 

Your regex requires that the host name portion starts with www. 您的正则表达式要求主机名部分以www.开头www. (this is not a requirement for URLs in general). (一般来说,这不是URL的要求)。 The URL you are testing does not include www. 您正在测试的URL不包含www. .


There are many other reasons why the regex is broken (you don't test past the first character after www. , your attempt to do so bans many characters that are allowed in URLs, etc) but that is why the URL you have isn't passing. 正则表达式损坏的原因还有很多(您不能测试www.之后的第一个字符,尝试这样做会禁止URL中允许的许多字符,等等),但这就是为什么您拥有的URL是“过去了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM