I'm using following rules to validate the username using jQuery validation method. I want to add another rule that username should contain only alphanumeric and underscore character. How can i add add开发者_如何学JAVAitional method for that rule. Is it possible that if user gives less than 4 characters, then I print the minimum length error message, and if the user gives invalid characters, then I give the invalid character error message? Thanks.
$(document).ready(function() {
$("#sform").validate({
rules: {
username: {
required: true,
minlength: 4
}
},
messages: {
username: "Minimum length 4.",
}
});
});
add like below
jQuery.validator.addMethod("alphanumeric", function(value, element) {
return !jQuery.validator.methods.required(value, element) || /^[a-zA-Z0-9_]+$/i.test(value);
}
, "Letters, numbers or underscores only please");
and apply below
$('validatorElement').validate({
rules : {
username : { alphanumeric : true }
}
});
Using remote ajax validation do this
$("#sform").validate({
rules: {
username: {
required: true,
minlength: 4,
remote: 'alphanumertic.php'
//check on server
}
},
messages: {
username: "Minimum length 4.",
}
});
Probably the best way is to validate using regular expression which can be found on
jQuery validate: How to add a rule for regular expression validation?
Regular Expression for alphanumeric and underscores
The validation plugin comes with additional-methods.js, which includes an alphanumeric plus underscore validation:
http://ajax.aspnetcdn.com/ajax/jquery.validate/1.10.0/additional-methods.js
Same rules as above:
$('validatorElement').validate({
rules: {
username: { alphanumeric : true }
}
});
Old question but I am adding my answer so that one can get help
One can use following:
create a function that will encapsulate our validation test, with the following signatures:
function mytest(value, element, params){...}
After we have the function established, we can then attach it to the jQuery Validation plug-in. To do this, we call the validator object's addMethod() function.
My Code:
$(document).ready(function() {
// other code
// :
// :
$.validator.addMethod(
"passwd",
function(value, element, regexp) {
var re = new RegExp(regexp);
return this.optional(element) || re.test(value);
},
"Invalid input"
);
$("#add_user_form").validate({
rules:{
user_name: {
required: true,
minlength: 5,
maxlength: 15,
noSpace: true
},
password: {
required: true,
minlength: 8,
passwd: "((?=(.*\\d.*){2,})(?=(.*[a-zA-Z].*){2,})(?=(.*[@#$(){}!~,.!^?/|+=-_%].*){2,}).{8,20})"
}
},
messages:{
user_name: {
required: "*",
minlength: " at least 5 characters",
maxlenght: " only 15 characters",
noSpace: " No space Please"
},
password: {
required: "*",
minlength: " Your password must be at least 8 characters long",
passwd: " Invalid Password choice"
}
});
//
// more code in document.ready
good links:
Starting With jQuery - How to Write Custom Validation Rules
How to add a rule for regular expression validation?
精彩评论