Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery datepicker and custom validation

I need to add custom validation(I think) for validating input from an user. Here's my use case: I'm using the jquery ui datepicker for selecting dates, with localization like this:

$.datepicker.setDefaults( $.datepicker.regional[ currentLocale ] );

I use the bassistance validation plugin, and using rules for date:true and such does not work with different formats(or if they do please tell me how!). So I've made my own date validation methods like this

   $.validator.addMethod("validDate", function(value) {
        return parseDateString(value) != null;
    }, jQuery.validator.messages.date);

This all works very well except for the fact when selecting a date in the datepicker the validation is fired before the value of the componet is changed! So I actually validate the previous value....

Does anyone have a solution for me? Thanks in advance:)

like image 345
Runar Halse Avatar asked Jan 08 '11 13:01

Runar Halse


1 Answers

You could trigger validation upon the user closing the datepicker popup:

$("#birthdate").datepicker({
    onClose: function() {
        /* Validate a specific element: */
        $("form").validate().element("#birthdate");
    }
});

Using validate's element() function will enable you to validate a particular field immediately.

I've created an example here in which any date who's year != 2011 will trigger failed validation.

like image 80
Andrew Whitaker Avatar answered Sep 22 '22 15:09

Andrew Whitaker