2015-01-21 142 views
1

我想覆蓋jQuery Validator插件提供的'required'和'minlength'驗證器的功能。以下是我的代碼:jQuery驗證器功能覆蓋問題

jQuery(".form-cls").validate({ 
      errorElement: "span", 
      errorClass: "error-msg", 
     rules: { 
      email:{ 
       required:true, 
       email:true, 
       alreadyExistEmail: true 
      }, 
      user_email:{ 
       required:true, 
       email:true 
      }, 
      password:{ 
       required: function (element) { 
            return checkIfPasswordIsRequired(); 
           }, 
           minlength: function (element) { 
            return passwordLengthCheck(element); 
           } 
        } 
     } 
    }); 

function checkIfPasswordIsRequired() 
    { 
     if(jQuery("#facebook_id").length > 0 || jQuery("#linkedin_id").length > 0 || jQuery("#xing_id").length > 0) { 
      if(jQuery("#facebook_id").val() != "" || jQuery("#linkedin_id").val() != "" || jQuery("#xing_id").val() != "") { 
       return false; 
      } 
     } 
     return true; 
    } 





function passwordLengthCheck(element) 
    { 
     if(element.value.length < 6) 
     { 
      return false; 
     } 
     else 
     { 
      return true; 
     } 
    } 

現在,這裏密碼字段中第一個檢查工作的罰款是「必需的」,但第二次檢查是不工作的。如果已經檢查了它,我的console.log(element.value.length),它會在每次更改/更改值時在密碼字段中給出值的長度,但取決於函數passwordLengthCheck中的條件,它從不顯示/顯示錯誤。請幫助!

+0

爲什麼不使用自定義的驗證密鑰,而不是默認的'required'? – Runcorn 2015-01-21 08:22:14

+0

@Runcorn可以給你一個使用自定義驗證的例子嗎? – 2015-01-21 08:25:13

+0

看到這個http://stackoverflow.com/questions/241145/jquery-validate-plugin-how-to-create-a-simple-custom-rule – Runcorn 2015-01-21 09:06:54

回答

1

要檢查字段長度,只需添加minlength屬性的<input>標籤,像

<input id="pw" name="pw" minlength="6" type="password"> 

添加一些自定義的驗證,使用addMethod()

jQuery.validator.addMethod("func", function(value, element) { 
    return this.optional(element) || check expression here; 
}