Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery datepicker: validate date mm/dd/yyyy

I have a textbox and a datepicker next to it and I am using asp.net and the user can enter the date as well select the date from datepicker.

How would you validate if the date is entered correct?

  <script type="text/javascript"> 
        $(document).ready(function () { 
            $('#<%=StartDate.ClientID%>').datepicker({ showOn: 'button', 
                    buttonImage: '../images/Calendar.png', 
                    buttonImageOnly: true, onSelect: function () { }, 
                    onClose: function () { $(this).focus(); } 
            }); 
        }); 
    </script> 
like image 671
Nick Kahn Avatar asked Apr 26 '10 17:04

Nick Kahn


People also ask

How to validate date format in jQuery datepicker?

parseDate('dd/mm/yy', value); } catch (err) { ok = false; } return ok; }); $(". datefield"). datepicker({ dateFormat: 'dd/mm/yy', changeYear: true }); }); This overrides the default way that jQuery will parse a date (mm/dd/yy) to dd/mm/yy.

How do you validate a date field with jQuery validation plugin?

Below jQuery code shows exactly the same thing. $(function() { $('#btnSubmit'). bind('click', function(){ var txtVal = $('#txtDate'). val(); if(isDate(txtVal)) alert('Valid Date'); else alert('Invalid Date'); }); });

How do you check if the date is in dd mm yyyy format in Javascript?

The toISOString() method returns a string formatted as YYYY-MM-DDTHH:mm:ss. sssZ . If the ISO representation of the Date object starts with the provided string, then the date string is valid and formatted as DD/MM/YYYY .


3 Answers

I use this handler for validate input:

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

Hope, it'll be useful for somebody

like image 182
katrin Avatar answered Oct 02 '22 22:10

katrin


If you're using ASP.NET, you can use an ASP.NET Compare Validator [ASP.NET Date Validator].

<asp:TextBox ID="tb" runat="server"></asp:TextBox>

<asp:CompareValidator ID="cv" runat="server" 
ControlToValidate="tb" ErrorMessage="* Please enter a valid date!" Text="*" 
Operator="DataTypeCheck" Type="Date"></asp:CompareValidator>

**** Update**

I took the javascript that was executed by the Compare Validator above and wrapped a custom jQuery Validation method around it:

<script type="text/javascript">
    $(document).ready(function () {

        $.validator.addMethod("truedate", function (value, element, params) {
            function GetFullYear(year, params) {
                var twoDigitCutoffYear = params.cutoffyear % 100;
                var cutoffYearCentury = params.cutoffyear - twoDigitCutoffYear;
                return ((year > twoDigitCutoffYear) ? (cutoffYearCentury - 100 + year) : (cutoffYearCentury + year));
            }

            var yearFirstExp = new RegExp("^\\s*((\\d{4})|(\\d{2}))([-/]|\\. ?)(\\d{1,2})\\4(\\d{1,2})\\.?\\s*$");
            try {
                m = value.match(yearFirstExp);
                var day, month, year;
                if (m != null && (m[2].length == 4 || params.dateorder == "ymd")) {
                    day = m[6];
                    month = m[5];
                    year = (m[2].length == 4) ? m[2] : GetFullYear(parseInt(m[3], 10));
                }
                else {
                    if (params.dateorder == "ymd") {
                        return null;
                    }
                    var yearLastExp = new RegExp("^\\s*(\\d{1,2})([-/]|\\. ?)(\\d{1,2})(?:\\s|\\2)((\\d{4})|(\\d{2}))(?:\\s\u0433\\.)?\\s*$");
                    m = value.match(yearLastExp);
                    if (m == null) {
                        return null;
                    }
                    if (params.dateorder == "mdy") {
                        day = m[3];
                        month = m[1];
                    }
                    else {
                        day = m[1];
                        month = m[3];
                    }
                    year = (m[5].length == 4) ? m[5] : GetFullYear(parseInt(m[6], 10));
                }
                month -= 1;
                var date = new Date(year, month, day);
                if (year < 100) {
                    date.setFullYear(year);
                }
                return (typeof (date) == "object" && year == date.getFullYear() && month == date.getMonth() && day == date.getDate()) ? date.valueOf() : null;
            }
            catch (err) {
                return null;
            }
        }, "Please enter an actual date.");

        $("#form1").validate();

        $("#one").rules('add',
        {
            truedate: {
                cutoffyear: '2029',
                dateorder: 'mdy'
            }
        });
    });

</script>

<input id="one" />
like image 42
dochoffiday Avatar answered Oct 02 '22 22:10

dochoffiday


I'm using a mix of Katrin & Doc Holiday's approach, using the datepicker control's parseDate utility method in a custom validator I've called isDate.

Just change the format argument in parseDate to the appropriate value (reference: http://docs.jquery.com/UI/Datepicker/parseDate).

    $(document).ready(function()
    {
        $.validator.addMethod('isDate', function(value, element)
        {
            var isDate = false;
            try
            {
                $.datepicker.parseDate('dd/mm/yy', value);
                isDate = true;
            }
            catch (e)
            {

            }
            return isDate;
        });

        $("#form1").validate();

        $("#dateToValidate").rules("add", { isDate: true, messages: {isDate: "Date to Validate is invalid."} });
    });

It's probably not best practice for the validator to be referencing a UI control but what the heck. :)

like image 30
Trawler Avatar answered Oct 02 '22 20:10

Trawler