jQuery validator and datepicker click not validating

Quote OP:

“I have to select the datepicker twice. ie; 1 click to select and it inputs the data correctly. 2nd click to clear the error message.”

That’s because validation is normally triggered on keyup and blur events. Since you’re using a date-picker to interact with the field, rather than the keyboard, you’re interfering with the normal triggering events.

Your code is supposed to compensate, but is over-kill…

$(function() {
        $("#datepicker").datepicker({ ... })
.on('changeDate', function(ev) {
    if($('#datepicker').valid()){
       $('#datepicker').removeClass('invalid').addClass('success');   
    }
 });
    });

You only need to call the .valid() method on the field whenever the value changes.

$(function() {
    $("#datepicker").datepicker({ ... })
        .on('changeDate', function(ev) {
            $(this).valid();  // triggers the validation test
            // '$(this)' refers to '$("#datepicker")'
        });
});

However, this is basically the same as you had before.

What is changeDate supposed to be? Is this something defined by your datepicker plugin? That’s not a standard jQuery event, so likely the whole problem. Try the standard change event instead….

$(function() {
    $("#datepicker").datepicker({
        changeMonth: true,
        changeYear: true,
        yearRange: '2011:2037',
        dateFormat: 'dd/mm/yy',
        minDate: 0,
        defaultDate: null
    }).on('change', function() {
        $(this).valid();  // triggers the validation test
        // '$(this)' refers to '$("#datepicker")'
    });
});

Leave a Comment