Jquery-validation: .isValid() method, without marking the element

Created on 24 Jul 2014  路  7Comments  路  Source: jquery-validation/jquery-validation

I need a way to check if an element is valid while only returning true/false, _without_ marking the element with the error class. Similar to, but also unlike .valid() which will actually mark the element with the classname valid/error and update the message.

Does anyone have an elegant solution for this? This is what I came up with for now:

isValid: function() {
    var validator = $( this[ 0 ].form ).validate();
    var cleanElement = validator.clean( this ),
        checkElement = validator.validationTargetFor( cleanElement ),
        result = true;

    result = validator.check( checkElement ) !== false;

    return result;
}

The reason for this is that on my onkeyup function, I wanted to delay the validation by a second or two before it got validated again.

For example:
I have two rules for email, one for required, and one for valid email address. If user tries to submit without a value, the user originally gets the err message is "required". Once focused and they start inputting, even with one key, the err message immediately changes to "not valid". Obviously not UX friendly, the delay's goal is to allow the user enough time to input their correct email.

onkeyup: function (element, event) {
...
clearTimeout(timeout);
if ( $(element).hasClass('error') && event.keyCode !== 9 ) {
    // if the element is valid, validate it as normal 
    // .valid() would of validated, we want to check only if its valid first
    if ( $(element).isValid() ) {
        $element.valid();
    } 
    // else the element is not valid, give the user a delay on input 
    // before returning another error
    else {
        // On each keyup, give user a second to enter something
        timeout = setTimeout(function () {
            console.log('give it a sec')
            $element.valid();
        }, 1000);
    }
}
}

Most helpful comment

BTW: how this issue can be a duplicate of a later one? :stuck_out_tongue_closed_eyes:

All 7 comments

there is a check(element) method which would help you, but it seems it is not part of the public API
https://github.com/jzaefferer/jquery-validation/blob/master/src/core.js#L582

Duplicate of #1220.

Wrong reference, should be #1349

+1

BTW: how this issue can be a duplicate of a later one? :stuck_out_tongue_closed_eyes:

Haha LOL, duplicate one of later issue.

there is a check(element) method which would help you, but it seems it is not part of the public API
https://github.com/jzaefferer/jquery-validation/blob/master/src/core.js#L582

For anyone that finds this page through Google like I did, this is the answer (I missed it when I first saw the page because of the comments after it about duplicates). Check is not in documentation but it does work.

function isValid(el) {
    return $("form").validate().check(el);
}
Was this page helpful?
0 / 5 - 0 ratings