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?

4 Answers 4

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?

Sign up to request clarification or add additional context in comments.

2 Comments

Do I have to include moment.js library to use this?
Yes, the isValid function is part of the moment object.
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

2 Comments

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?
Invalid dates are accepted by this method. 40/40/2016 results in 1557439200000 for instance.
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');
            }
        });
});

3 Comments

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.
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.
I got around my issue with the use of .blur() this using the onClose event/property of the datepicker to trigger the validation.
-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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.