JQuery.validate - one rule on blur only; the rest should be normal?

前端 未结 2 2047
清歌不尽
清歌不尽 2020-12-01 23:37

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条回答
  • 2020-12-01 23:53

    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.

    0 讨论(0)
  • 2020-12-02 00:04

    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.

    0 讨论(0)
提交回复
热议问题