jQuery Validate remote onblur only but allow onkey

2020-07-27 01:43发布

问题:

I am trying to do a jquery remote validation to see if a name is unique or not, but i do not want to do remote validation on every single onkekup event, however i would like to do this on blur event(when user leaves the textbox). but with current code i have below, it fires up after 2nd character is pressed. i would like to continue to have rest of the rules fire on onkeyup like required and minlength and rules for other elements. is there not a property to control this behavior, just for single rule? i noticed a set default that does for entire form.

  elem.validate({
        ignore: "",
        rules: {
            name: {
                required: true,
                minlength: 2,
                maxlength: 60,
                remote: {
                    url: "/api/IsUniqueName",
                    onkeyup: false,
                    type: "get",
                    contentType: "application/json",
                    data: {
                        name: function () {

                            return elem.find('input[name^=Name]').val();
                        }
                    },
                    headers: {
                        RequestVerificationToken: Indexreqtoken
                    },
                }
            },
            ...

回答1:

You cannot put the onkeyup option inside of the remote rule... that's not how the remote method works. The remote method can only accept the same options as jQuery .ajax() and nothing else.

However, you cannot restrict or control the triggering events on a "per rule" basis. These events are captured for the whole form or individually on each field, they can not be confined to a specific rule.

If you want to restrict the plugin's onkeyup function to certain fields, then you would use a conditional within the onkeyup option...

$('#myForm').validate({
    onkeyup: function(element, event) {
        if ($(element).attr('name') == "name") {
            return false; // disable onkeyup for your element named as "name"
        } else { // else use the default on everything else
            if ( event.which === 9 && this.elementValue( element ) === "" ) {
                return;
            } else if ( element.name in this.submitted || element === this.lastElement ) {
                this.element( element );
            }
        }
    },
    ignore: [],  // <- note the proper format for the "ignore nothing" setting.
    rules: {
        name: {
            required: true,
            minlength: 2,
            maxlength: 60,
            remote: {
                url: "/api/IsUniqueName",
                ....

EDIT:

Quote OP:

"is there not a property to control this behavior, just for single rule?"

No, the triggering events cannot be controlled on a "per rule" basis. They can only be controlled for the whole form OR for a specific field, as I've shown above.

https://stackoverflow.com/a/21313848/594235