0

Possible Duplicate:
Using Javascript, how do I make sure a date range is valid?

I am allowing users to input dates on the page, and one of my testers is correctly breaking the database save with the following error:

SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.

Is there an existing function out there to validate this on the client side in jQuery or JavaScript before the date is sent to the server so I can give feedback to the user? I'd prefer not to have to write my own (possibly incomplete one).

Thanks

Community
  • 1
  • 1
Adam Levitt
  • 10,316
  • 26
  • 84
  • 145

4 Answers4

2

javascript overloads the > and < comparison operators to work with dates.

if (yourDate > new Date('1/1/1753 12:00:00 AM') && 
    yourDate < new Date('12/31/9999 11:59:59 PM')) {
    // date is in your valid range
} else {
    // date is not in your valid range
}

http://jsfiddle.net/jbabey/UB9NR/

keep in mind javascript validation is for performance only and adds no security; it should always be supplemented with server side validation.

jbabey
  • 45,965
  • 12
  • 71
  • 94
1

You can try jQuery validation plugin to handle this at client side. But do not do it only in client. Always Always Always Do it on Server Side before Sending to DB.

As per the jQuery docs, the code can be simple as this.

$("#myform").validate({
  rules: {
    field: {
      required: true,
      date: true
    }
  }
});

If you want custom date format, this answer is worth to look

Community
  • 1
  • 1
Shyju
  • 214,206
  • 104
  • 411
  • 497
1

Use Datepicker plugin http://jqueryui.com/demos/datepicker/#min-max And restrict the user to input wrong range using date range method

http://jqueryui.com/demos/datepicker/#date-range

CODE

$(function() {
        $( "#from" ).datepicker({
            defaultDate: "+1w",
            changeMonth: true,
            numberOfMonths: 3,
            onSelect: function( selectedDate ) {
                $( "#to" ).datepicker( "option", "minDate", selectedDate );
            }
        });
        $( "#to" ).datepicker({
            defaultDate: "+1w",
            changeMonth: true,
            numberOfMonths: 3,
            onSelect: function( selectedDate ) {
                $( "#from" ).datepicker( "option", "maxDate", selectedDate );
            }
        });
    });
Imdad
  • 5,942
  • 4
  • 33
  • 53
1

You need date js library. I think this function is what you are looking for Date.validateDay. see the documentation

nabeel
  • 931
  • 9
  • 16