0

我正在使用jQuery.validation插件来验证表单。表单上有一个名为“survey_url”的可选字段。如果此字段为空白,我不想对其进行验证,但是如果有一个值,我想确保它是有效的 URL。

我有以下规则,但尽管我没有将survey_url 设置为“必需”,但即使它没有值,它也会被标记为无效 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 仅在具有值的情况下才被验证为 URL?

4

2 回答 2

1

您的脚本中必须有其他内容,因为您提供的内容可以按预期工作:http: //jsfiddle.net/ryleyb/ztDwh/1/

您应该能够提交该表单,只填写标题,而 URL 中没有任何内容。如果您输入一个 URL,它必须是正确的 URL 格式。听起来像你想要的?

于 2012-09-24T14:54:56.240 回答
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");
 }
 }
于 2012-09-23T17:02:02.620 回答