TCM
TCM

Reputation: 16920

Better alternatives to know whether a control is valid in JavaScript?

I want to know whether a control is valid or not in JavaScript. Is there a direct client side API available in Asp.Net which can tell me whether a control is valid or not?

Eg. If I have 2 validators attached to a textbox, I need a function that can tell me whether the textbox is valid or not. If even 1 validator is not valid then it should return false.

I can't seem to find a function that can give me this. Here is a little helper that I wrote which does the job but is inefficient:

function isControlValid(control) {
    for (i = 0; i < Page_Validators.length; i++) {
        var validator = Page_Validators[i];
        var controlId = validator.controltovalidate;
        if ($(control).attr('id') == controlId && validator.isvalid == false) {
            return false;
        }
    }
    return true;
}

Anybody has any better alternatives?

Upvotes: 2

Views: 1400

Answers (1)

Ramesh
Ramesh

Reputation: 13266

The below code should work.

function isControlValid(control) {
    var validators = $(control).Validators;
    var isValid = true;
    Array.forEach(validtors, function(item) {
        isValid = isValid && (item.isvalid === true);
    });
    return isValid;
}

UPDATE

This is better than the one you proposed because the entire page validators is not iterated. Only the ones associated with the control is used for iteration. $(control).Validators is used to retrieve the validators associated with the control.

Upvotes: 1

Related Questions