I am trying to use the jQuery Validation Plugin (http://jqueryvalidation.org/) on a address street field where people have to confirm if their address don't contain a house number (some just forget to write it or whatever).
So I wrote a custom rule and extended the error message with two buttons like this:
// comes from an external file
jQuery.extend(jQuery.validator.methods, {
containsnum: function(value, element) {
return this.optional(element) || /^.*(\d).*$/.test(value);
}
});
// comes from an external file
jQuery.extend(jQuery.validator.messages, {
containsnum: "Does this address have a house number? <button id='yes' class='btn btn-mini'>yes</button> <button id='no' class='btn btn-mini'>no</button>"
});
then the actual validation code
$(document).ready(function() {
var xx = $('#customer-data-form').validate({
debug:true,
ignore: ":hidden",
rules: {
Anschrift: {
containsnum:true
}
}
});
/* check for house number */
$(document).on('click',"#no",function(e){
console.log('no')
e.preventDefault();
$('#Anschrift').rules( "remove", "containsnum" );
xx.element('#Anschrift');
});
$(document).on('click',"#yes",function(e){
console.log('yes')
e.preventDefault();
$('#Anschrift').focus();
});
});
It works pretty well but under some circumstances the confirmation (and removal of the rule) just works on the second click on the yes/no button.
I've setup a fiddle with steps to reproduce this behavior.
http://jsfiddle.net/CC3zH/2/
The goal is, to make the confirmation of that message work on first click under all circumstances and then I hope for a hint, how to separate the buttons from the Error message string.
I already experimented with errorPlacement etc, but didn't find a simple solution without rewriting all the functions to display the errors.
Thanks for any hint.