remove dynamic validation with Jquery Validate plugin
i have a simplified version of my problem here: http://www.arianhojat.com/temp/jquery/dynamic_validate/test.html
Basically i had an email rule, and based on a checkbox i remove it... but it still isn't being removed... I tried moving it to its own rule with "add", then trying to remove via its accompanying "remove" function but still same problem.
So after you fill out your First Name, try submitting. it will error about the Email field... then check the checkbox, it should remove the validation for #email, it kinda only removes half of it. like if you try submitting with just firstname, it allows it... but now type something in the email field and try submitting... it will error saying its not valid (but the validation has been removed?)
Thanks!
Code is here for reference:
$(document).ready(function(){
$("#contactForm").validate({
onfocusout: false,
debug: true,
rules: {
fname: {
required: true
}
},
messages: {
fname: {
required: "* Please enter a first name"
}
},
errorLabelContainer: "#messageBox",
wrapper: "li",
submitHandler: function(form) {
alert('Submitted');
return false;
}
});
$("#email").rules("add", {
required: true,
email: true,
messages: {
required: "* Please enter a sweet email address",
email: "* Please enter a sweet valid email address"
}
});
$('#no_email').bind('change', function(event) {
if( $(this).attr('checked') ) {
console.log('removed?');
$("#email").rules("remove"); //, "required email" ... still doesnt work if spec开发者_StackOverflow中文版ify the rules to remove
} else {
console.log('re-added?');
$("#email").rules("add", {
required: true,
email: true,
messages: {
required: "* Please enter an awesome email address",
email: "* Please enter an awesome valid email address"
}
});
} //else
$("#contactForm").validate().element( "#email" );
});
});
....
<form id="contactForm" action="doesnt_exist_yet2.html" method="post">
<ul id="messageBox"></ul>
<div style="">
<p>First name:</p>
<input type="text" name="fname" id="fname" class="fname" maxlength="100"/>
</div>
<div style="">
<p>Your Email Address</p>
<input type="text" name="email" id="email" class="email" maxlength="100"/>
</div>
<br/><br/>
<input type="checkbox" name="no_email" id="no_email" /> Turn off validation for EMAIL
<input type="submit" name="submit_btn" id="submit_btn" value="Submit">
</form>
I think I solved it, can't have #email and email rule. i change my field to #myemail and think it works now. errrrr!
精彩评论