2011-06-24 20 views
2

我已經申請上一個輸入框2個addMethods合併2個addMethods於一體,爲驗證

注:我需要一個像空的錯誤和有效的URL 2個的錯誤消息,如果其中一人是無效的在一個addMethod。

1 - 需要檢查 2 - 檢查URL驗證。

有沒有辦法將兩者合併並得到相同的結果?

jQuery.validator.addMethod("complete_req", function (val, elem) { 

    var value = $.trim($("#linkTypeDd").val()); 
    if (value == "2") 
    { 
     if (val.length == 0) { 
      return false; 
     } 
      return true; 
    } 
},""); 

    jQuery.validator.addMethod("complete_url", function (val, elem) { 

     var value = $.trim($("#linkTypeDd").val()); 
     if (value == "2") { 
      // if no url, don't do anything 
      if (val.length == 0) {return true;} 

      // if user has not entered http:// https:// or ftp:// assume they mean http:// 
      if (!/^(https?|ftp):\/\//i.test(val)) { 
       val = 'http://' + val; // set both the value 
       $(elem).val(val); // also update the form element 
      } 

      // now check if valid url 
      // http://docs.jquery.com/Plugins/Validation/Methods/url 
      return "Suppose this is url rejex"; 
     } 

     return true; 
    }); 

    jQuery.validator.messages.required = ""; 
    var validator = $("#footer-form").validate({ 
     debug: true, 

     submitHandler: function (form) { 
      $(form).ajaxSubmit(formoptions); 
     }, 

     invalidHandler: function (e, validator) { 
      var errors = validator.numberOfInvalids(); 
      if (errors) { 
       var message = errors == 1 ? 'You missed 1 field. It has been highlighted.' : 'You missed ' + errors + ' fields. They have been highlighted.'; 
       showMessage("#error", message); 
       $("#success").hide(); 
      } 
      else { 
       $("#error").hide(); 
      } 
     }, 

     rules: 
     { 
      DisplayName: "required", 
      UrlName: "required", 
      ExternalPath: { 
       complete_req : true, 
       url: "complete_url" 
      } 
     }, 

     errorClass: "invalid", 
     validClass: "valid", 
     errorContainer: "#error" 
    }); 

回答

0

我認爲將兩個規則合併爲一個唯一的方法。即將兩種方法中的邏輯合併爲一個,並將其轉換爲單個添加方法和單個規則。

var value = $.trim($("#linkTypeDd").val()); 
    if (value == "2") 
    { 
     if (val.length == 0) { 
      return false; //means required 
     } 
     else 
     { 
      // here you have to do the checking for valid url 
     } 
    } 
+0

感謝您的回覆。我理解你在說什麼,但是如何通過URL錯誤消息顯示多個錯誤消息,例如所需的錯誤。這是重要的事情,我很多谷歌搜索後找不到答案。任何想法? – Pirzada

+0

您可以做一件事情,在方法中首先檢查所需條件,如果失敗則表示顯示所需的錯誤。如果所需的條件成功意味着檢查有效的網址,如果失敗則意味着顯示有效網址的錯誤 –

+0

您可以編輯我的代碼並顯示給我。試過但不能工作。 – Pirzada