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

故事扮演 提交于 2019-11-27 09:39:01

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!