jquery datepicker and custom validation

2019-03-31 00:35发布

问题:

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:)

回答1:

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.