Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding 'async: false' in JQuery validation

I've written a JQuery validation method for checking a custom field. To check the data I call a server-side script using AJAX, which in turn, returns true or false. If false, the response will also contain an error message:

var errorMessage;
var rtErrorMessage = function() {
    return errorMessage;
}

jQuery.validator.addMethod('customvalidation', function(value, element) {
    var valid = true;
    var url = '/validation?data=' + value;
    $.ajax({
        url: url,
        type: 'get',
        dataType: 'json',
        async: false,
        success: function(responseData) {
            if (responseData && !responseData.isValid) {
                errorMessage = responseData.errorMessage;
                valid = false;
            }
        }
    });

    return valid;
}, rtErrorMessage);

This works, however turning of synchronicity means that the browser freezes during the request. This is rather annoying and JQuery even recommend against it... but what is the alternative?

Thanks in advance.

like image 612
Jonathan Avatar asked May 07 '26 08:05

Jonathan


2 Answers

Use the remote method of jquery validate - if you return true or false you get the default error message and the the field is marked as valid/invalid.

If you return any other string like "this is my error message" the error message displayed will be the string you return.

If the docs say otherwise they are out of date I am using jquery validate 1.10.0

like image 107
Dr Blowhard Avatar answered May 09 '26 08:05

Dr Blowhard


The standard way of doing this is to just relinquish control to a callback function, letting the user know that a problem has occurred once the database makes a decision. Obviously if you really want a function that returns the result of the ajax call, you will need async=false, but there are other ways of doing it. You don't need to wait for each ajax call to return true in order to prevent form submits until all form elements are validated--you simply need a check some flags (which the callbacks can set) to make sure the form elements have been validated. This may involve a little waiting if some of the validation requests aren't done yet, but in normally users are slower than ajax.

TLDR: use ajax async, and don't wait for callbacks until you have to. If you can't have a couple of processes going, then you're stuck with async=false.

like image 42
AlexMA Avatar answered May 09 '26 09:05

AlexMA



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!