Add regex to jquery.validate

You need to add a regex check to my jquery.validate script.

I have it:

$().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" }, } }); 

});

And I would like to check the specific characters that are allowed in the database for passwords when the user enters his data here:

  <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"/> 

What's the best way to add regular expression validation to a required field, such as password or username, using the jquery.validate plugin from bassisstance: http://docs.jquery.com/Plugins/Validation

Basically, I need to make sure that the passwords and user names they create have only 0-9, letters, and a pair of special characters.

+7
source share
2 answers

Ok, you can add your own validation method with addMethod , like

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

AND,

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

The above expression will return true if regexp passes, false if it is not. Modify it according to your needs.

+3
source

All Articles