2012-09-23 57 views
0

我正在使用jQuery.validation插件來驗證表單。名爲'survey_url'的表單上有一個可選字段。如果這個字段是空白的,我不希望它被驗證,但是如果有一個值,我想確保它是一個有效的URL。jQuery驗證 - 只驗證字段爲URL,如果它有一個值

我有以下的規則,但儘管我還沒有設置SURVEY_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,如果它有一個值?

+0

您可以創建自己的自定義規則,看看[問題]的答案(http://stackoverflow.com/questions/241145/jquery-validate-plugin-how-to-create-a-simple - 自定義規則)在這裏...可能對你有用 – alekperos

回答

1

因爲你給了什麼必須有別的東西在你的腳本怎麼回事,它按預期工作:http://jsfiddle.net/ryleyb/ztDwh/1/

您應該能夠提交該表格只有標題填寫,並且URL中沒有任何內容。如果您輸入網址,則必須使用正確的網址格式。聽起來像你想要的?

+0

你是絕對正確的。剛回到它並且工作正常。 – Undistraction

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"); 
} 
} 
相關問題