最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Bootstrap DatePicker - Validate Date - Stack Overflow

programmeradmin1浏览0评论

I have a bootstrap datepicker set up such that the startDate = '1/1/1990', but if the user enters the date manually in the text box to something such as 1/1/201 (likely mistype of 1/1/2014), the date is just blanked out when they change focus. Is there a way such that if they attempt to leave the field with an invalid date that instead of having a blank field that I can specify something like today's date, or even change the background color and not allow for the user to leave that field?

Thank you for your help.

I have a bootstrap datepicker set up such that the startDate = '1/1/1990', but if the user enters the date manually in the text box to something such as 1/1/201 (likely mistype of 1/1/2014), the date is just blanked out when they change focus. Is there a way such that if they attempt to leave the field with an invalid date that instead of having a blank field that I can specify something like today's date, or even change the background color and not allow for the user to leave that field?

Thank you for your help.

Share Improve this question edited Jun 13, 2014 at 20:31 user3739011 134 bronze badges asked Jun 13, 2014 at 20:25 dmoore1181dmoore1181 2,1223 gold badges34 silver badges66 bronze badges 1
  • 1 use onChange event handler on date input to check your date after it was changed. – Denis O. Commented Jun 13, 2014 at 20:36
Add a ment  | 

3 Answers 3

Reset to default 3

You can also set the date field to readonly, in this way user can only select correct date format from datepicker.

example:

http://www.w3schools./tags/att_input_readonly.asp

You can use the jquery validation plugin for the color, showing msg for the invalid date. And in that case for validating the date value with present date you have to add a custom validation method to it like :-

           $.validator.addMethod("presentDate", function(value, element) {

                if(new Date(value).getTime() >= new Date().getTime()){
                    return true;
                } else {
                    return false;
                }
            });

I have figured out that I can simply detect when the value of the date has been set to '' and go from there with what I want to change:

$('#StartDate').change(function()
{
    if (this.value === '')
    {
        alert('Start date is now set to empty string, do work here');
    }
});
发布评论

评论列表(0)

  1. 暂无评论