12

i have set a jquery class:

$(function() {
            $( ".datepickerIT" ).datepicker({
                showOtherMonths: true,
                selectOtherMonths: true,
                showAnim: "clip",
                dateFormat: "dd/mm/yy",
                minDate: "01/01/1925",
                maxDate: "31/12/2050",
                changeMonth: true,
                changeYear: true,
                yearRange: "1925:2050",
                regional: "it"                      
            });
        });

I want to add a date check control that alert if user input not is a valid date

How can add to the class ".datepickerIT" a check like this?

onClose: function(dateText, inst) {
        try {
            $.datepicker.parseDate('dd/mm/yy', dateText);
        } catch (e) {
            alert(e);
        };

And what plugin i must include into head section?

Manlio
  • 121
  • 1
  • 2
  • 6

4 Answers4

11

Date.parse is not recommend to use as there are still many differences in how different hosts parse date strings. [1][2]

I would use moment for date validation.

moment(newDate, 'DD/MM/YYYY', true).isValid()

jsfiddle: http://jsfiddle.net/dw8xyzd4/

[1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse [2] Why does Date.parse give incorrect results?

Community
  • 1
  • 1
Razan Paul
  • 13,618
  • 3
  • 69
  • 61
8

You can validate the date in following ways (you don't need a plugin for it):-

$(document).ready(function(){
    $("#datepicker").datepicker();
    $("#datepicker").blur(function(){
        val = $(this).val();
        val1 = Date.parse(val);
        if (isNaN(val1)==true && val!==''){
           alert("error")
        }
        else{
           console.log(val1);
        }
    });
});

Working fiddle

UPDATE: Correct approach is mentioned by @Razan Paul

Gaurav Kalyan
  • 1,897
  • 2
  • 14
  • 21
  • I tried your fiddle and `Date.parse` for day 31 in month which doesn't have such day returns value oter than NaN. Got any solution for that? – Zaimatsu Jun 16 '16 at 10:29
  • 3
    Invalid dates are accepted by this method. 40/40/2016 results in 1557439200000 for instance. – Joeblade Jul 20 '16 at 07:44
5

Date.parse() does not support dd/mm/yyyy and datepicker getDate sets date to current on any parse error hence this bespoke check using new Date(yyyy, mm, dd) to verify date parts are consistent after conversion:

$(function() {
    $(".datepickerIT")
        .datepicker({
            showOtherMonths: true,
            selectOtherMonths: true,
            showAnim: "clip",
            dateFormat: "dd/mm/yy",
            minDate: "01/01/1925",
            maxDate: "31/12/2050",
            changeMonth: true,
            changeYear: true,
            yearRange: "1925:2050",
            regional: "it"                      
        })
        .on('blur', function() { // This check is for dd/mm/yyyy format but can be easily adapted to any other
            if(this.value.match(/\d{1,2}[^\d]\d{1,2}[^\d]\d{4,4}/gi) == null)
                alert('Invalid date format');
            else {
                var t = this.value.split(/[^\d]/);
                var dd = parseInt(t[0], 10);
                var m0 = parseInt(t[1], 10) - 1; // Month in JavaScript Date object is 0-based
                var yyyy = parseInt(t[2], 10);
                var d = new Date(yyyy, m0, dd); // new Date(2017, 13, 32) is still valid
                if(d.getDate() != dd || d.getMonth() != m0 || d.getFullYear() != yyyy)
                    alert('Invalid date value');
            }
        });
});
Y.B.
  • 3,526
  • 14
  • 24
  • This should be the accepted answer. The completeness and the detail in the comments really helps to understand what is going on. I actually understand regex a bit more because of this. Thanks for your answer Y.B., it was used by me. – Alexander Dixon Jun 20 '19 at 13:45
  • I'm having an unwanted behavior where clicking in the picker bases the data to blur and fire the validation. It makes sense that this happens, but makes the blur validation less flexible. – GoetzOnline Sep 04 '19 at 19:09
  • I got around my issue with the use of .blur() this using the onClose event/property of the datepicker to trigger the validation. – GoetzOnline Sep 05 '19 at 14:25
-1
$(document).ready(function(){

//  Check in date 
    $("#in" ).datepick({
        dateFormat: "mm/dd/yy",
        minDate:"0+1",
        maxDate: "2years",
        changeMonth:true, 
        changeYear:true,    
        onSelect:function(date_text,inst){
            var from = new Date(date_text);
            $( "#out" ).datepicker( "option", "minDate",from);
        }       


    });

//  Check out date  



});

Note:-Here in is your field name and datepick is your plugin name.

Anuj Dubey
  • 43
  • 3