3

How can I get JQuery Validation to fire the remote rule on an empty field? The server decides whether the field is required or not, so I need the remote rule to fire when calling valid even when the field is empty- currently, if the field is empty, the rule will not be called.

Sparky
  • 98,165
  • 25
  • 199
  • 285
Lock
  • 5,422
  • 14
  • 66
  • 113
  • The plugin does not work that way... that's what the `required` rule is for. – Sparky Jan 16 '15 at 06:48
  • @Sparky- I realise that, hence why I am asking the question. There has to be a way. I wander if you can overwrite the required rule.. – Lock Jan 16 '15 at 06:53

2 Answers2

2

Created a new validator method which doesn't call the optional function and is setup to handle the ajax call as synchronous.

$.validator.addMethod("synchronousRemote", function (value, element, param) {

    var previous = this.previousValue(element);
    if (!this.settings.messages[element.name]) {
        this.settings.messages[element.name] = {};
    }
    previous.originalMessage = this.settings.messages[element.name].remote;
    this.settings.messages[element.name].remote = previous.message;

    param = typeof param === "string" && { url: param } || param;

    if (previous.old === value) {
        return previous.valid;
    }

    previous.old = value;
    var validator = this;
    this.startRequest(element);
    var data = {};
    data[element.name] = value;
    var valid = "pending";
    $.ajax($.extend(true, {
        url: param,
        async: false,
        mode: "abort",
        port: "validate" + element.name,
        dataType: "json",
        data: data,
        success: function (response) {
            validator.settings.messages[element.name].remote = previous.originalMessage;
            valid = response === true || response === "true";
            if (valid) {
                var submitted = validator.formSubmitted;
                validator.prepareElement(element);
                validator.formSubmitted = submitted;
                validator.successList.push(element);
                delete validator.invalid[element.name];
                validator.showErrors();
            } else {
                var errors = {};
                var message = response || validator.defaultMessage(element, "remote");
                errors[element.name] = previous.message = $.isFunction(message) ? message(value) : message;
                validator.invalid[element.name] = true;
                validator.showErrors(errors);
            }
            previous.valid = valid;
            validator.stopRequest(element, valid);
        }
    }, param));
    return valid;
}, "Please fix this field.");
Lock
  • 5,422
  • 14
  • 66
  • 113
  • I'm new to web dev and was wondering why you chose to call it `synchronousRemote`? Isn't the default `remote` method synchronous by itself in that it waits for a reply from the server before validating the input? – user51462 Jul 20 '20 at 05:35
0

If the field is empty, then there is no data to evaluate.

In other words, none of the validation rules (except for required) are fired when an input is empty... that's just how the plugin's methods are written.

However, the only way to change how the standard methods operate would be to over-ride them with your own. Use the .addMethod() method to write a new remote method that makes the field required. Look at the source code for the existing remote method and use that within your custom method. You'll need to remove any parts that utilize this.optional(element) as that's what keeps it from firing on empty input field.

Sparky
  • 98,165
  • 25
  • 199
  • 285
  • I don't see how your workaround would work. You said that only the `required` validation rule is fired on empty inputs, so why would a custom rule be fired on empty? I might just edit the plugin file directly- it's a small site that has only 1 remote rule (the one in question). – Lock Jan 16 '15 at 06:58
  • @Lock, the last sentence of my answer explains what part keeps a rule from firing on an empty field. Use `.addMethod()` to over-ride the rule leaving out the part that keeps it from firing. – Sparky Jan 16 '15 at 07:01
  • @Lock, I left out the exact code as the default `remote` method is very lengthy. However, I think you'll just need to leave out the first few lines when you copy it over to your custom method. – Sparky Jan 16 '15 at 07:03
  • Thanks sparky. I've removed the `this.optional(element)` part and the rule runs, however it runs after the form has been submitted. It's as if it is not waiting for the ajax call to complete (I click submit and it submits, however before the page disappears, the error message pops up briefly). – Lock Jan 16 '15 at 07:13
  • OK got it working. Will post an answer. Had to use this post http://stackoverflow.com/questions/7247250/jquery-validation-not-waiting-for-remote-validation-to-return-true-considers-fo to help with the synchronous stuff. – Lock Jan 16 '15 at 07:19
  • @Lock, yes, that makes sense. Since nothing else like a `required` rule would be stopping the field from being submitted, you'd have to disable `async`. Normally the `async` option or any other `ajax` option for `remote` is declared along with the rule itself and not hard-coded. – Sparky Jan 16 '15 at 17:40