开发者

jquery validate - check which rule is not fulfilled

开发者 https://www.devze.com 2023-04-11 04:26 出处:网络
I have a form with several fields and using jQuery validation plugin. My input has several rules: { required : \"#somecheckbox:not开发者_C百科(:checked)\",

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

{
    required : "#somecheckbox:not开发者_C百科(: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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号