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.
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.
This is a problem with how focusout
and click
events interact. If you look around, you'll see that it is a very common issue that click
events are not triggered correctly when a focusout
event is also triggered on the element losing focus. Many solutions are proposed, but one that works in your case is changing your $.on
handlers to key on mousedown
instead of click
, like so:
$('#customer-data-form').on('mousedown',"#no",function(e){
console.log('no')
e.preventDefault();
$('#Anschrift').rules( "remove", "containsnum" );
xx.element('#Anschrift');
});
$('#customer-data-form').on('mousedown',"#yes",function(e){
console.log('yes')
e.preventDefault();
$('#Anschrift').focus();
});
Working here: http://jsfiddle.net/ryleyb/CC3zH/3/