JQuery.validate - one rule on blur only; the rest

2019-09-05 07:13发布

I've worked on a fiddle to show the simple validation that I'm trying to do for my user ID field:

  1. Make it required (validate as aggressively as possible)
  2. Set a minimum length (validate as aggressively as possible)
  3. Set a maximum length (validate as aggressively as possible)
  4. Run an AJAX call to ensure user ID doesn't already exist (I want to only run this on blur)

I'm not using the validate() - remote rule because I wanted to have a custom object returned instead of just a simple string. If that's possible with remote and it only calls the rule on blur, then I can try for that. (All of my AJAX responses adhere to a set object definition.)

HTML

<form action="#" method="get" id="register-wizard">User ID:
    <br />
    <input type="text" class="form-control required confirm-me" id="User_UserId" name="User.UserId" autocomplete="off" />
    <div class="loader user-id hide" style="display: none;"><i class="icon-spinner icon-spin icon-large"></i> (Checking...)</div>
    <p>
        <button id="next">Next</button>
    </p>
</form>

JavaScript

var $wizardForm = $("#register-wizard");
var $validator = $wizardForm.validate({
    rules: {
        "User.UserId": {
            required: true,
            minlength: 3,
            maxlength: 125,
            userIdCheck: true
        }
    }
});

$("#next").click(function (e) {
    e.preventDefault();    
    //do validations before moving onto the next tab in the wizard
    var $valid = $wizardForm.valid();
    if (!$valid) {
        $validator.focusInvalid();
        return false;
    }
});    
jQuery.validator.addMethod("userIdCheck", function (value, element) {
    var validator = this;
    this.startRequest(element);    
    var $loader = $(".loader.user-id");    
    $.ajax({
        url: "/echo/json/",
        type: "POST",
        data:{
            json: JSON.stringify({
                text: 'some text'
            }),
            delay: 1
        },
        success: function (result) {
            console.log("result: ")
            console.log(result);

            validator.stopRequest(element, true);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert("A server error occurred.\n\n" + textStatus);
        },
        beforeSend: function () {
            $loader.show();
        },
        complete: function () {
            $loader.hide();
        }
    });

return "pending";
}, "The user ID is already in use");

Here's my fiddle: http://jsfiddle.net/eHu35/3/

2条回答
狗以群分
2楼-- · 2019-09-05 08:06

I encountered the same problem, and use this way works, not use the remote method:

$.validator.addMethod("userIdCheck", function(value, element, params) {
    if (event.type == "blur" || event.type == "focusout") {
        var result;
        $.ajax({url: "path", async: false,
                success: function(data){
                  result = data;
              }})
        return result;
    } else {
        return true;
    }       
}, "The user ID is already in use");

But this don't work on firefox, event undefined. So I modefied the source code(anyone has another way?):

function delegate( event ) {
    var validator = $.data( this[ 0 ].form, "validator" ),
        eventType = "on" + event.type.replace( /^validate/, "" ),
        settings = validator.settings;
        // add event to validator
        validator.event = event;
        if ( settings[ eventType ] && !this.is( settings.ignore ) ) {
            settings[ eventType ].call( validator, this[ 0 ], event );
        }
    }

then we can use in this way:

$.validator.addMethod("userIdCheck", function(value, element, params) {
    var eventType = this.event.type;
    if (eventType == "blur" || eventType == "focusout") {
        var result;
        $.ajax({url: "path", async: false,
                success: function(data){
                  result = data;
              }})
        return result;
    } else {
        return true;
    }
}, "The user ID is already in use");

Not prefect enough, but this is the only way I find to solve this problem.

查看更多
男人必须洒脱
3楼-- · 2019-09-05 08:08

Quote Title: "one rule on blur only; the rest should be normal?"

No, the various triggering events, like onfocusout, onkeyup, etc., are triggered on a "per field" basis. You cannot have one rule on a field, say min, triggered normally on all events, while another rule for the same field, say remote, is triggered only by onfocusout. (You can, however, have different events for different fields).

In most of the SO threads on this topic I've seen, the user will disable onkeyup in order to prevent the constant premature triggering of the remote rule. When testing a re-captcha code, for example, disabling onkeyup is required as a new code is generated every time one fails.

查看更多
登录 后发表回答