3

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.

5
  • Is there a reason you absolutely NEED to use async: false? Why not allow the user to continue to fill out the form, and received the error message when the server sends you the response? Commented Feb 19, 2013 at 13:33
  • @Kyle Unfortunately, it seems so. Otherwise the validation method completes (and returns valid) before the AJAX request has finished. Commented Feb 19, 2013 at 13:37
  • I believe the library you are using has a remote option. Look at the docs. Commented Feb 19, 2013 at 13:56
  • @epascarello Correct. The docs confirm that remote is only able to handle true/false responses. Commented Feb 19, 2013 at 13:59
  • @Jonathan Instead of using the custom validation method of the plugin, have you tried adding your own .on('blur', function... method? That should remove the error you mentioned in your previous comment. Commented Feb 19, 2013 at 14:01

5 Answers 5

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

+1, 99.99% of the time, there's never a reason to re-invent the wheel.
1

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.

1 Comment

And by processes (last sentence), I don't mean it literally. Javascript is single-process.
1

I think what would have to happen is that your validator should always return false, unless the field has been previously validated (that is, no changes had occurred since last validation and the validation was successful). This would require some additional handlers, obviously. In fact, you might want to rethink how you do this, a bit. Most validators working with Ajax probably immediately "invalidate" a control and invoke some de-bounced method in the onchange handler, the method does its thing firing some Ajax which then validates the control or not, and upon receipt, flags the control as valid or not. Using something like this, you would never put the Ajax invocation in the validator method, but you would use the aforementioned flag. I'd write some code to demonstrate but my primary computer is down for the moment.

Comments

0

Just as an aside to this post, I have actually found that async:false was breaking my validation, I had a reported issue where the user feedback was "I tried submitting XXXX but I got an error and then when I tried to submit again it would not let me". Only occurred when I had async: false on remote validation requests. I thought I needed it to be async but turns out I don't. Making them true again made everything hunky dory. Very weird.

Comments

-1

If you have to hit the server to perform the validation, then submit the form as normal and (in the event of errors) return a prepopulated form with the error messages. Don't use Ajax at all, it just means you have to send the data to the server twice.

3 Comments

From a UX-standpoint, I find that showing the user error-messages while they are filling in the form is much more user-friendly than having them fill in a form, submit it, wait for a response, fix any errors, etc.
@robertklep — I'm working on the assumption that the function is running onsubmit. Since the server needs to be hit anyway, they are going to be waiting for a response either way.
OP writes "...for checking a custom field", so I would assume that they aren't submitting the form at that point, just validating one piece of input (hmm why is SO removing my @Quentin prefix?)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.