Search code examples
jqueryvalidationjquery-validatevalidationrules

jquery validate - check which rule is not fulfilled


I have a form with several fields and using jQuery validation plugin. My input has several rules:

{
    required : "#somecheckbox:not(:checked)",
    regex : "\d{10}",
    maxlength : 10,
    remote : [object Object],
    __dummy__ : true
} 

What I want to know is, how I can check which of these rules are not fulfilled (or is some specific rule valid or not). I know that this is possible as remote validation does not fire ajax requests until others are fullfiled, but I cannot find in jquery.validate.js how it is done.


Solution

  • I have figured out how to do this by examining source of jQuery validate plugin, so I made my own function to tap into 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;
    } 
    

    Usage is simple:

    $("#myform").validate().ruleValidationStatus($("#myField"))
    

    And sample result is:

    {
        required : true,
        regex : true,
        maxlength : true,
        remote : false,
        __dummy__ : true
    } 
    

    From this object it is easy to see what rules are not satisfied.