2012-12-09 140 views
7

需要將正則表達式檢查添加到我的jquery.validate腳本中。將正則表達式添加到jquery.validate

我有這樣的:

$().ready(function() { 
    $("#myBlahForm").validate({ 

    rules: { 
     someName: { 
      required: true, 
      minlength: 5, 
      maxlength: 8, 
     }, 
     somePassword: { 
      required: true, 
          minlength: 5, 
      maxlength: 8, 
     }, 
     someConfirmPassword: { 
      required: true, 
      equalTo: "#somePassword" 
     }, 
    }, 
    messages: { 
     someName: { 
      required: "Please create your username", 
     }, 
     somePassword: { 
      required: "Please create a password", 
     }, 
     someConfirmPassword: { 
      required: "Please re-enter your password", 
      equalTo: "Passwords must match" 
     }, 
    } 
}); 

});

而且我想檢查是否有在DB允許的密碼特定字符,當用戶將在此輸入自己的數據:

<label for="someName">Username</label> 
    <input type="text" id="someName" name="someName" placeholder="Create a Username"/> 

    <label for="somePassword">Password</label> 
    <input type="password" id="somePassword" name="somePassword" placeholder="Create a Password"/> 

    <label for="someConfirmPassword">Confirm Password </label> 
    <input type="password" id="someConfirmPassword" name="someConfirmPassword" placeholder="Verify your Password"/> 

什麼是正則表達式檢查添加到必填字段等的最佳方式作爲密碼或用戶名使用jquery.validate插件來自bassisstance:http://docs.jquery.com/Plugins/Validation

基本上,我需要確保他們創建的密碼和用戶名只有0-9,字母和一些特殊字符。

+1

的可能重複[JQuery驗證:如何添加正則表達式驗證的規則] (http://stackoverflow.com/questions/280759/jquery-validate-how-to-add-a-rule-for-regular-expression-validation) – ABMagil

回答

26

好了,你可以添加使用addMethod自定義的驗證方法,如

$.validator.addMethod("regx", function(value, element, regexpr) {   
    return regexpr.test(value); 
}, "Please enter a valid pasword."); 

而且,

... 
$("#myBlahForm").validate({ 

    rules: { 
     somePassword: { 
      required: true , 
      //change regexp to suit your needs 
      regx: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])\w{6,}$/, 
      minlength: 5, 
      maxlength: 8 
     } 
    } 
3
required: function(element){ 
    return /[a-zA-Z0-9]/.test($('#someConfirmPassword').val()); 
} 

如果正則表達式通過,上述表達式將返回true,否則返回false。改變它以適應您的需求。

+0

非常感謝你! ;-) – mzalazar