jQuery validate not working as expected

主宰稳场 提交于 2019-12-20 07:29:26

问题


I'm using jQuery validate() and when I simply have:

$("#myForm").validate({
    onfocusout: function (valueToBeTested) {
        if($(valueToBeTested).hasClass('required')){
            if(this.element(valueToBeTested)){
                $(valueToBeTested).addClass('valid');
            } else{
                $(valueToBeTested).addClass('invalid');
            };
        };
    }
    rules:
        {
      ...(rules here)
    }
}); 

it works fine. But when I try to add something like onkeyup or submitHandler:

$("#myForm").validate({
    onfocusout: function (valueToBeTested) {
        if($(valueToBeTested).hasClass('required')){
            if(this.element(valueToBeTested)){
                $(valueToBeTested).addClass('valid');
            } else{
                $(valueToBeTested).addClass('invalid');
            };
        };
    },
    submitHandler: function(i){
        var badForm = false;
        var errmsg = "<img src=\"invalid.png\"/><br/>";
        var $required_fields = $(".required");
        $required_fields.each( function(i) { 
            if(!($(i).valid())){
                errmsg += $(i).name + " is required<br/>";  
                badForm = true;
            }

            if(badForm){
                alert("bad");
                $('#errdiv').html(errmsg).show();
                window.scrollTo(0,0);   
            }
        });
    },
    rules:
        {
       ...
    }
}); 

it starts not working: 1) in this scenario, it seems to never even enter the submitHandler block. Same when I try to duplicate the onfocusout functionality inside an onkeyup block. 2) when the second block is present, it messes with the onfocusout block in the sense that the onfocusout block will work the first time on any given field, then not again.

I feel that I'm missing something obvious since I think I'm doing what the documentation says. I want the validation to happen on all three. The onfocusout and onkeyup are pretty much the same, but the submitHandlershould do the same, plus populate and show the error div.

What am I missing here?

Thanks.


回答1:


Completely remove your custom onfocusout and onkeyup functions. You are totally misusing these.

The onfocusout and onkeyup functions only control how validation is triggered and you have broken this functionality.

Adding/removing the error/valid classes is already being done automatically by default on keyup and focusout. If you need to over-ride how classes are applied, you would write custom highlight and unhighlight functions. However, based on your code, I see no reason to do this either. You would only need to change the error class from the default error into invalid.

errorClass: "invalid",
validClass: "valid" // <- default value

As far as the submitHandler, as per docs it only fires when the form is valid, so it's useless to put a conditional inside that tests for validity.

You also would never put code in the submitHandler that has anything to do with the error messages or their HTML structure. You would use errorPlacement and/or errorElement for this. The success option is used for leveraging the message label elements when the field is valid, since they're normally hidden in this case. You would use showErrors, errorContainer, and errorLabelContainer to construct a centralized error message box.

I suggest you refer to the documentation to learn how the various options and functions are properly used.

In other words, you seem to be trying to force the plugin to do what it's already supposed to be doing. By improperly over riding these designated options, you're breaking the plugin, and it's still somewhat unclear what you're ultimately trying to achieve. If you're only trying to over-ride the default assigned classes, you don't need to re-write all the default functionality, just use the errorClass and validClass options.

$('#myForm').validate({
    errorClass: "invalid",
    validClass: "valid", // <- already the default value, not needed to specify
    rules: {
        ...
    }
});

Simple demo: http://jsfiddle.net/9ax47efu/


EDIT:

After many comments, it was determined that the OP wants to switch the validation behavior from "Lazy" to "Eager".

Defaults modified to remove "Lazy" validation...

onkeyup: function(element, event) {
    var excludedKeys = [
        16, 17, 18, 20, 35, 36, 37,
        38, 39, 40, 45, 144, 225
    ];
    if (event.which === 9 && this.elementValue(element) === "" || $.inArray(event.keyCode, excludedKeys) !== -1) {
        return;
    } else {
        this.element(element);
    }
},
onfocusout: function(element) {
    if (!this.checkable(element)) {
        this.element(element);
    }
}

DEMO 2: http://jsfiddle.net/c8zq6bzu/



来源:https://stackoverflow.com/questions/36361616/jquery-validate-not-working-as-expected

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