Archive for September 24, 2009
How To : Reset the Validation Rules on a Dynamic Form (JQuery + Validation Plugin)
1I created an application which handles requests, after choosing a request type the form fields are fetched and a form is generated. It’s completely AJAX based, thus the page is never refreshed. I ran into a problem though, rules from previous form generations persisted between request changes. The answer is simple, add an empty “rules” property to the validate() call. Note that internally the Validate plugin stores the form validation information in the JQuery data space so my first shot was to erase this data, which didn’t work.
—————- code snippet from jquery.validate.js —————-
line 35 $.data(this[0], ‘validator’, validator);
—————- code snippet —————-
…
myform.validate({
rules: {}, // REQUIRED TO RESET THE RULES LIST!!
onkeyup: false,
onfocusout: false,
onclick: false,
submitHandler: function(form) {
…
—————- ajax-based validation method example —————-
jQuery.validator.addMethod(“validatepair”, function(value, element) {
var checkresult = false;
$.ajax({
url: “validation_url”,
async: false, // important!
data: {
“value1″:$(‘#value1id’).val(),
“value2″:$(‘#value2id option:selected’).val()
},
dataType: “jsonp”,
success: function(data){
checkresult = data.valid;
}
});
return checkresult;
}, “Value1 does not match with the choosen value2 option.”);