开发者

jQuery disable/re-enable validators on a page

When I need to disable/re-enable validator I usually use jQuery code like so:

      ValidatorEnable($('[id*=DueDateRequiredValidator]')[0], false);

and to re-enable it back:

      ValidatorEnable($('[id*=DueDateRequiredValidator]')[0], true);
            var validator = $('[id*=DueDateRequiredValidator]')[0];
            validator.isvalid = true;
            ValidatorUpdateDisplay(validator);

And it works. But now I need to disable/re-enable a large number of validators, but only a subset of validators, not entire set on a page. There's too many of them to refer each validator by "id".

I tried something like this开发者_运维知识库 but it didn't work, don't know why:

      $.each(Page_Validators, function(index, validator) {
                if ( validator.CssClass == "noinjuries" )

                { ValidatorEnable(validator, false); } 


      }); 

What's the best way to do this, if any?


Yeah, try this first

if ($(validator).hasClass('noinjuries')) { /* disable validator */ }


I found the following javascript code on a blog, it uses a ValidationGroup to toggle Validation controls, but you could just as easily remove the if (Page_Validators[i].validationGroup == validationGroupName) line and toggle the whole collection of Validators.

You will have to add your own enabling code after the 'ValidatorEnable' method call.

function HasPageValidators() {
    var hasValidators = false;

    try {
        if (Page_Validators.length > 0) {
            hasValidators = true;
        }
    }
    catch (error) {
    }

    return hasValidators;
}

function ValidationGroupEnable(validationGroupName, isEnable) {
    if (HasPageValidators()) {
        for (i = 0; i < Page_Validators.length; i++) {
            if (Page_Validators[i].validationGroup == validationGroupName) {
                ValidatorEnable($('[id*=DueDateRequiredValidator]')[0], true);
            }
        }
    }
}

Edit: Victor, based on your comment, I think you could get the same results by adding Attributes to your controls. This would group them without using the ValidationGroups, and you can access the attributes from JavaScript.

In your code behind, you need to set the attributes for your Validation controls like so:

SampleValidator1.Attributes.Add("myGroupName", "sample1");
SampleValidator2.Attributes.Add("myGroupName", "sample2");

Then, in the Javascript function, rather than this line `if (Page_Validators[i].validationGroup == validationGroupName) {', use this:

if (Page_Validators[i].getAttribute('myClass') == 'sample1') {

That should get you what you want without Groups, but sorry - you will have to set the Attribute


One Last Edit: I was making this harder than it needs to be. I haven't tried it, but if you want to get the CSS class of an object in JavaScript it is .className, not .class. Try that before any of my earlier suggestions.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜