Tuesday 8 April 2014

JQuery Validation for Array of Input Elements

1) Add validation rule as :-


$().ready(function() {
// validate the comment form when it is submitted
$("#signupForm").validate({
rules: {
"category[]": "required"
},
messages: {
"category[]": "Please select category",
}
});
});
2) Find the checkform function in jquery.validation.js and replace with below code:-
checkForm: function() {
this.prepareForm();
for ( var i = 0, elements = (this.currentElements = this.elements()); elements[i]; i++ ) {
if (this.findByName( elements[i].name ).length != undefined && this.findByName( elements[i].name ).length > 1) {
for (var cnt = 0; cnt < this.findByName( elements[i].name ).length; cnt++) {
this.check( this.findByName( elements[i].name )[cnt] );
}
} else {
this.check( elements[i] );
}
}
return this.valid();
}
if wants to makes it work specific to a form not globally just add below code to specific file:-
$.validator.prototype.checkForm = function () {
//overriden in a specific page
this.prepareForm();
for (var i = 0, elements = (this.currentElements = this.elements()); elements[i]; i++) {
if (this.findByName(elements[i].name).length != undefined && this.findByName(elements[i].name).length > 1) {
for (var cnt = 0; cnt < this.findByName(elements[i].name).length; cnt++) {
this.check(this.findByName(elements[i].name)[cnt]);
}
} else {
this.check(elements[i]);
}
}
return this.valid();
}

No comments:

Post a Comment