问题
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