JQuery Validate plugin submitting when it shouldn't

自古美人都是妖i 提交于 2019-12-23 01:51:15

问题


I am trying to validate my form by printing out a message if the email is invalid, if the password does not meet minimum requirements or if the password and confirm password fields do not match.

To verify the plugin is working correctly, I am only testing for the validity of the email. The validator seems to be working for a second before the form is submitted regardless of whether the form is valid or not and I can't seem to figure out why.

Also, the 'email isn't valid' message isn't being printed out.

I have been trying to figure this one out for quite some time and I appreciate any suggestions.

Thanks in advance!

JavaScript:

$('#signUpForm').validate({ // initialize the plugin
    errorPlacement: function(error, element) {},
    rules: {
        email: {
            required: true,
            email: true
        }
    }
});

$('#signUpForm').submit(function(e){
    e.preventDefault();
    if($(this).valid()){
        $(this).submit();
    }else{
        return false;
    }           
});

Form:

<form id="signUpForm" method="post" action="signup.php">
    <input id="signUpEmail" name="email" class="form-control"> 
    <input id="signUpPassword" name="password" class="form-control" type="password"> 
    <input id="confirmPassword" name="confirmPassword" class="form-control" type="password"> 
</form>

回答1:


This configuration is all wrong...

$('#signUpForm').validate({ // initialize the plugin
    ....
});

$('#signUpForm').submit(function(e){
    ....     
});

Your .submit() handler is totally redundant and totally interfering with the proper operation of the jQuery Validate plugin, which automatically captures the button click and blocks the submit event already.

In other words, the code within your .submit() handler is functionally identical to what the plugin is already doing for you. You don't need it and it's breaking validation.


Your errorPlacment callback function is empty so that's going to stop all error messages from displaying...

errorPlacement: function(error, element) {},

It should simply look something like this...

$('#signUpForm').validate({ // initialize the plugin
    rules: {
        email: {
            required: true,
            email: true
        },
        password: {
            required: true,
            minlength: 8,
            maxlength: 12
        },
        confirmPassword: {
            equalTo: '#signUpPassword'
        }
    }
});

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


Refer to the documentation and SO Tag Wiki page for proper usage.



来源:https://stackoverflow.com/questions/28328668/jquery-validate-plugin-submitting-when-it-shouldnt

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