我正在使用 jQuery.validation 插件来验证表单。表单上有一个名为“survey_url”的可选字段。如果此字段为空,我不希望它被验证,但是如果有值,我想确保它是有效的URL。
我有以下规则,但尽管我没有将survey_url设置为'required',但即使它没有值,它也会被标记为无效的URL:
//form validation rules
form.validate({
errorClass: "help-inline",
rules: {
"webcast[title]": "required",
"webcast[survey_url]":
{
url: true
}
},
messages: {
"webcast[title]":
{
required: "Please enter a title for this Webcast."
},
"webcast[survey_url]":
{
required:"You must enter a valid URL, or leave blank."
}
},
submitHandler: function(form) {
form.submit();
}
});
我的规则应该是什么样的,以便Survey_url只有在有值的情况下才会被验证为网址?
答案 0 :(得分:1)
您的脚本中肯定会有其他内容,因为您提供的内容会按预期运行:http://jsfiddle.net/ryleyb/ztDwh/1/
您应该能够仅填充标题提交该表单,并且URL中没有任何内容。如果您输入了URL,则它必须采用正确的URL格式。听起来像你想要的?
答案 1 :(得分:0)
url=$("#survey_url").val();
url=$.trim("#survey_url");
if (url!=""){
if(/^([a-z]([a-z]|\d|\+|-|\.)*):(\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?((\[(|(v[\da-f]{1,}\.(([a-z]|\d|-|\.|_|~)|[!\$&'\(\)\*\+,;=]|:)+))\])|((\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])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=])*)(:\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})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)|((([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})|[!\$&'\(\)\*\+,;=]|:|@)){0})(\?((([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(url)) {
alert("valid url");
} else {
alert("invalid url");
}
}