2

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Goran Obradovic
  • 8,951
  • 9
  • 50
  • 79

1 Answers1

2

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.

Goran Obradovic
  • 8,951
  • 9
  • 50
  • 79
  • What is __dummy__ there? – pabben Feb 18 '16 at 17:15
  • @pabben this was very long time ago, so I do not remember anymore, but even if I do not use jQuery anymore, I believe it is one of 2 things: I wanted to add a rule that is always true in order to test the output, or plugin needs one that is true in order to add some validation element to the form. Maybe is nothing, just for illustration. Sorry for not remembering, but I think you can just ignore it. – Goran Obradovic Feb 18 '16 at 21:45