Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return value from withing a setTimeout function

I am using Google Maps Autocomplete to set the value of an input, and I use http://jqueryvalidation.org/ to validate the minimum length. Problem is Google Maps Autocomplete (and any asynchronous plugin) takes a moment to populate the input as it needs to access the remote server, and the jQuery Validation Plugin validates before the value is populated. For a demo, see http://jsbin.com/digiz/1.

Is it possible to delay the validation for a specific rule on a specific element?

If not, is it possible to create a new validation method which has a brief delay? For instance, see below for my feeble attempt. The first console.log displays only the entered characters before "clicking" a Google provided result, but the second displays the updated value, so I know I am on the right track (I hope!). I have not, however, figured out how to return the validation condition from within the setTimeout function.

Any help would be appreciated!

jQuery.validator.addMethod("minlengthDelay", function(value, element, params) {
    console.log(element.value);
    var t=this;
    window.setTimeout(function(){
        console.log(element.value);
        return t.optional(element) || $.trim(element.value).length>=params;
        }, 100);
    }, jQuery.format("Please enter at least {0} characters."));
like image 631
user1032531 Avatar asked Apr 25 '26 23:04

user1032531


1 Answers

Is it possible to delay the validation for a specific rule on a specific element?

No, I don't think so. The jQuery validation plugin does not support asynchronous functions.

I have not, however, figured out how to return the validation condition from within the setTimeout function.

This is impossible - you cannot return a value from an asynchronous callback. You would need to offer a callback or return a promise, but that would require support for this by the function accepting your validation callback.

like image 165
Bergi Avatar answered Apr 27 '26 12:04

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!