0

I'd like to know if it was possible to validate a chosen date from a datepicker control from jQuery UI. I know it is possible to select a date, bounded by a date format, but it is also possible to enter a date manually.

I'd like to check, when a date is entered manually, if this date is valid. e.g. 31/04/2015 would be invalid, same for 29/02/2015.

I have some example code, as well as an fiddle with the same exact code as a demo purpose.

In this sample code, I'm using some dirty code imo. Is there an easier way to do this?

HTML


<input type="text" id="txtDatepicker"/>

Javascript


$("#txtDatepicker").datepicker({
    dateFormat: "dd/mm/yy",
    onClose: function() {
        var textdate = $(this).val();
        var day = parseInt(textdate.substring(0, 2));
        var month = parseInt(textdate.substring(3, 5));
        switch(month)
        {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                if(day < 1 || day > 30)
                {
                    alert("Invalid date!");   
                }

            default:
                if(day < 1 || day > 31) {
                    alert("Invalid date!");   
                }
        }
    }
});

As mentioned before, this doesn't always check if the current year is a leap year, so for example 29/02/2015 would be considered "valid" in this code.

How do I do this? I am bound to the dateformat "dd/mm/yy" because of my region and also because it's an internship assignment, so other formats are not allowed.

Thanks in advance!

Demo: jsFiddle

Jorrex
  • 1,503
  • 3
  • 13
  • 32

1 Answers1

0

I'm just going to post a short answer here.

I would recommend using Moment it makes handling dates easy! And is more reliable, and cleaner than parsing date strings.

You can install it with bower.

http://bower.io

https://github.com/moment/moment

Jeffpowrs
  • 4,430
  • 4
  • 30
  • 49