我正在尝试使用JavaScript验证网址,但由于某种原因它无效。当某人未输入任何网址时,会显示以下消息:
请输入有效的网址。(即http://)
我正在尝试修复它,但无法使其正常工作。
HTML5中是否有允许验证URL的技巧?
$(document).ready(function() {
$("#contactInfos").validate(
{ onfocusout: false, rules: {
phone: { number:true },
zipcode: { number:true },
website: { url:true }
},
messages: { phone: { number:"please enter digit only" },
zipcode: { number:"Plese enter digit only" },
website: { url: "Please enter valid URL.(i.e. http://)" }
}
});
验证网址的方法:
url: function(value, element) {
values=value.split(',');
for (x in values)
{
temp=values[x].trim();
temp1=this.optional(element) || /^(https?|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(temp);
if(temp1!=true)
{
return false;
}
}
return true;
},
答案 0 :(得分:43)
在html5中,你可以使用标签输入type =“url”:
<input type="url" />
您也可以使用自己的模式:
<input type="url" pattern="https?://.+" required />
在文章统一资源标识符(URI):通用语法[RFC3986] http://www.ietf.org/rfc/rfc3986.txt中,URI的正则表达式为:
^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
例如,将上述表达式与
匹配http://www.ics.uci.edu/pub/ietf/uri/#Related
导致以下子表达式匹配:
$1 = http: $2 = http $3 = //www.ics.uci.edu $4 = www.ics.uci.edu $5 = /pub/ietf/uri/ $6 = <undefined> $7 = <undefined> $8 = #Related $9 = Related
答案 1 :(得分:1)
没有协议,网址是否有效?
例如,目前http://google.com
是有效的网址,而google.com
则不是。{1}}。
同样,http://localhost
是有效的网址,而localhost
不是有效的网址。