JQuery single element validation not respecting rules
I cannot crack this one - I have a simple form with a textbox and button (not submit). I want users to enter an email address and when they press button, it will be added to a list of addresses displayed on a page. I only need to validate user entry to see if it is valid email address.
HTML:
<form id="inviteFriendsForm">
Email address: <input type="text" id="cemail" name="someEmail" value="" />
<input type="button" id="addEmail" value="Add email" />
</form>
jQuery:
$("#addEmail").click(function() {
var isValid = $("#inviteFriendsForm").validate({
rules: { cemail: { required: true, email: true } }
} ).element("#cemail");
if(isValid) {
alert($("#ce开发者_如何学编程mail").val());
}
else {
alert('Wrong email');
}
});
The problem I have is that isValid
variable is always true. Please note that alerts are there not because I would use it to indicate error to the user, code wise I just need to know whether I should continue processing user input or not.
Just for a record, I'm using jQuery Validation Plugin 1.8.0
Thanks a lot,
Antonin
- Make the button a submit button.
- Use validate's submitHandler property to change what happens when the form validates.
- Let validate's error display do its thing. If you need an alert instead of an error label, you can change how the error displays (check the documentation).
精彩评论