Recently, I have encountered a situation where I used jQuery validation plugin and needed to know which of validation rules are failing. After asking this question on http://stackoverflow.com/questions/7648727/jquery-validate-check-which-rule-is-not-fullfiled and receiving no answers for 15 days, I have spent some time to solve it by myself.
It turned out quite easy, after inspecting source code of plugin on https://github.com/jzaefferer/jquery-validation/blob/master/jquery.validate.js, I have found out that this can be done by adding my own function to it:
$.validator.prototype.ruleValidationStatus = function( element ) { element = $(element)[0]; var rules = $(element).rules(); var errors ={}; for (var method in rules ) { var rule = { method: method, parameters: rules[method] }; try { var result = $.validator.methods[method].call( this, element.value.replace(/\r/g, ""), element, rule.parameters ); errors[rule.method] = result ; } catch(e) { console.log(e); } } return errors; } |
This function returns list of validation rules with their results, and usage is simple:
$("#myform").validate().ruleValidationStatus($("#myField")); |