开发者

Temporarily disable a rule using jQuery Validate

My form has several rather complex validation rules and it became necessary for me to temporarily disable a given rule only to enable it later. It seemed pointless having to remove it and then add it again later so I needed a facility to disable a开发者_运维问答nd enable validation rules.


Starting with jquery.validate.js from version 1.8.1 I added in 2 case statments to the "rules" function so that the command switch statement reads as follows.

switch(command) {
case "add":
    $.extend(existingRules, $.validator.normalizeRule(argument));
    staticRules[element.name] = existingRules;
    if (argument.messages)
        settings.messages[element.name] = $.extend( settings.messages[element.name], argument.messages );
    break;
case "remove":
    if (!argument) {
        delete staticRules[element.name];
        return existingRules;
    }
    var filtered = {};
    $.each(argument.split(/\s/), function(index, method) {
        filtered[method] = existingRules[method];
        delete existingRules[method];
    });
    return filtered;
case "disable":
    if (!argument) {
        return false;
    }
    $.each(argument.split(/\s/), function(index, method) {
        existingRules[method].disabled=true;
    });
    break;
case "enable":
    if (!argument) {
        return false;
    }
    $.each(argument.split(/\s/), function(index, method) {
        existingRules[method].disabled=false;
    });
    break;
}

Then to implement this, in the "check" function we add a conditional to check the state of this disabled parameter we have set. Notably, if the rule has never been disabled/enabled then the value will be undefined, we assume here that if its undefined we're happy with the rule. The loop statement for this function now starts with:

for (var method in rules ) {
    var rule = { method: method, parameters: rules[method] };
    try {
        if (typeof rule.parameters["disabled"] === 'undefined' || rule.parameters["disabled"] == false)
        {
            var result = $.validator.methods[method].call( this, element.value.replace(/\r/g, ""), element, rule.parameters );
        } else {
            continue;
        }

Use this just as you would the "add" and "remove" facilty, e.g.

$('#email_address').rules("disable", "remote");
$('#email_address').rules("enable", "remote");

I hope this helps someone, I've been bashing my head against the wall trying to get to here.


I couldn't get your code to work, so I did a bit of playing around and the following will allow you to enable/disable validation for a particular field. hope this helps someone out.

on line 163 in jquery validation replace code to this: (adds the enable and disable rule)

if ( command ) {
    settings = $.data( element.form, "validator" ).settings;
    staticRules = settings.rules;
    existingRules = $.validator.staticRules( element );
    switch ( command ) {
    case "add":
        $.extend( existingRules, $.validator.normalizeRule( argument ) );

        // Remove messages from rules, but allow them to be set separately
        delete existingRules.messages;
        staticRules[ element.name ] = existingRules;
        if ( argument.messages ) {
            settings.messages[ element.name ] = $.extend( settings.messages[ element.name ], argument.messages );
        }
        break;
    case "remove":
        if ( !argument ) {
            delete staticRules[ element.name ];
            return existingRules;
        }
        filtered = {};
        $.each( argument.split( /\s/ ), function( index, method ) {
            filtered[ method ] = existingRules[ method ];
            delete existingRules[ method ];
        } );
        return filtered;
        break;
    case "disable":
         existingRules['disabled'] = true;
        break;
    case "enable":
        delete existingRules['disabled'];
        break;
    }
}

and in line 803 replace the following code: (ignores disabled rules)

for ( method in rules ) {
    rule = { method: method, parameters: rules[ method ] };
     try {
         if ('disabled' in rules){
             continue;
         }
         result = $.validator.methods[ method ].call( this, val, element, rule.parameters );
         
        // If a method indicates that the field is optional and therefore valid,
        // don't mark it as valid when there are no other rules
        if ( result === "dependency-mismatch" && rulesCount === 1 ) {
            dependencyMismatch = true;
            continue;
        }
        dependencyMismatch = false;

        if ( result === "pending" ) {
            this.toHide = this.toHide.not( this.errorsFor( element ) );
            return;
        }

        if ( !result ) {
            this.formatAndAdd( element, rule );
            return false;
        }
    } catch ( e ) {
        if ( this.settings.debug && window.console ) {
            console.log( "Exception occurred when checking element " + element.id + ", check the '" + rule.method + "' method.", e );
        }
        if ( e instanceof TypeError ) {
            e.message += ".  Exception occurred when checking element " + element.id + ", check the '" + rule.method + "' method.";
        }

        throw e;
    }
}

this will allow you to disable and enable valiadation rules, like so.

$('input[name="test"]').rules('enable');
$('input[name="test"]').rules('disable');
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜