我正在使用Jquery验证来验证网址:http://docs.jquery.com/Plugins/Validation/Methods/url
我发现正则表达式jquery用于不适合野外的URL。根据某些RFC,它可能是完美的,但是浏览器和服务器并不遵循RFC到字母,当然这并不罕见。看起来jquery验证正则表达式需要改进。
到目前为止,我发现jquery URL验证器错误地将带有{或}字符的URL标记为无效。但是这些字符在流行的浏览器中运行良好,并且在流行的网站上使用。
以下是野外URL的一个示例,但它无法正常运行jquery URL验证:
http://www.bestbuy.com/site/amazon-kindle-fire-hd-7-inch-tablet-with-8gb-memory-2nd-generation-black/2216082.p?id=1219070629225&skuId=2216082&ref=06&loc=01&ci_src=14110944&ci_sku=2216082&extensionType={adtype}:{network}&s_kwcid=PTC!pla!{keyword}!{matchtype}!{adwords_producttargetid}!{network}!{ifmobile:M}!{creative}&kpid=2216082&k_clickid=046dfb11-a86b-b669-52e3-00004228f299
Jquery验证使用以下正则表达式来验证URL:
url: function( value, element ) {
// contributed by Scott Gonzalez: http://projects.scottsplayground.com/iri/
return this.optional(element) || /^(https?|s?ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(value);
}
有没有人知道更好的方法来验证javascript或更好的可以处理真实网址的正则表达式中的网址?
答案 0 :(得分:0)
我最后通过为URI编码特殊字符的jquery url验证创建了一个包装器来解决这个问题。
$(function() {
"use strict";
var urlFunctionPtr = $.validator.methods["url"];
$.validator.methods["url"] = function() {
if(arguments.length > 0) {
arguments[0] = encodeURI(arguments[0]);
}
return urlFunctionPtr.apply(this, arguments);
};
});