jquery datepicker and custom validation

↘锁芯ラ 提交于 2019-12-21 05:31:47

问题


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.



来源:https://stackoverflow.com/questions/4634118/jquery-datepicker-and-custom-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!