jQuery DatePicker validation: Selected Date should be greater than Current date

Last Reply on Feb 08, 2018 11:31 PM By dharmendr

Posted on Feb 08, 2018 11:31 PM

My screen as follows From Date    Datepicker when i select the date less than the today date shows the message and date format of datepicker date dd-mm-yyyy. for that i written a code

$(function () {
    $("#datepicker").datepicker();
    $("#datepicker").on('change', function () {
        var date = Date.parse($(this).val());
        if (date < Date.now()) {
            alert('Selected date must be greater than today date');
            $(this).val('');
        }
    });
});


Date picker date format code as follows

$(function () {
    $("#datepicker").datepicker({ dateFormat: "dd-mm-yy" }).val()
});

in run mode when i select the date less than today date means message shows correctly  Selected date must be greater than today date. but date format is not changing , date format i get as 02/14/2018. the date format must 14-02-2018.

and selected date less than the today's date means message not showing Selected date must be greater than today date.

what is the mistake in my above code.

Posted on Feb 08, 2018 11:31 PM Modified on on Feb 09, 2018 12:47 AM

Hi narasiman,

Check the below example.

<style type="text/css">
    body
    {
        font-family: Arial;
        font-size: 8pt;
    }
</style>
From Date:
<input type="text" id="datepicker" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<link type="text/css" rel="Stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/start/jquery-ui.css" />
<script type="text/javascript">
    $(function () {
        Date.prototype.ddmmyyyy = function () {
            var dd = this.getDate().toString();
            var mm = (this.getMonth() + 1).toString();
            var yyyy = this.getFullYear().toString();
            return (dd[1] ? dd : "0" + dd[0]) + "-" + (mm[1] ? mm : "0" + mm[0]) + "-" + yyyy;
        };
        $("#datepicker").datepicker({ dateFormat: "dd-mm-yy" });
        $("#datepicker").on('change', function () {
            var selectedDate = $(this).val();
            var todaysDate = new Date().ddmmyyyy();
            if (selectedDate < todaysDate) {
                alert('Selected date must be greater than today date');
                $(this).val('');
            }
        });
    });            
</script>

Demo