Make jquery validate remote calls optional

Published: {ts '2020-06-30 00:00:00'}
Author: Steven Neiland
Site Url: http://www.neiland.net/article/make-jquery-validate-remote-calls-optional/

Sometimes it is necessary to disable remote validation calls when using jquery validate, fortunately its fairly straight forward once you figure it out. Of course the documentation is a little confusing so here is an example from my code archives.

Take the following scenario, you have a form where you are validating some field using back end remote validation. In this case an email but it could be anything. Now we are not so much concerned about the email being of a valid format, but rather that it does not already exist for another user.

Here is the form and associated validation code as you might design it.

...

As you can see when this form is submitted a call is made to the back end to verify that no user other than this one has this email. However this causes a delay and should be unnecessary if the email has not changed.

Using a dependency check to optionally fire the validation

What we can do to get around this is introduce another hidden input to track the original value of the email and tell jquery validation via its remote "depends" argument to only call the remote validation if the value of the email entered in the visible field does not match this original value.

... $('#testForm') .validate({ rules: { 'email': { required: true, remote: { param: { url: "some_ajax_validation_url", type: 'post', data: { email: function() { return $('[name="email"]').val(); }, userid: function() { return $('[name="userid"]').val(); } } }, depends: function(element){ // compare to original value and run remote check if different return ($(element).val() !== $('#originalemail').val()); } } } } });

Note: Never rely solely on front end validation. You should also enforce rules like this with back end validation and/or database constraints.