How can I check if user passes a valid date in javascript?
.net, asp.net, html, javascript
Solution
take a look at this library date.js http://code.google.com/p/jqueryjs/source/browse/trunk/plugins/methods/date.js
it has a useful function called fromString which will try and convert a string (based on Date.format) to a valid date object.
the function returns false if it doesn't create a valid date object - you can then try a different format before giving up if all return false.
here are some example formats you could test for:
Date.format = 'dd mmm yyyy';
alert(Date.fromString("26 Jun 2009"));
Date.format = 'mmm dd yyyy';
alert(Date.fromString("Jun 26 2009"));
Date.format = 'dd/mm/yy';
alert(Date.fromString("26/06/09"));
Date.format = 'mm/dd/yy';
alert(Date.fromString("06/26/09"));
Date.format = 'yyyy-mm-dd';
alert(Date.fromString("2009-06-26"));
Josh
Problem
I have a javascript function that checks for a date range. Is there any way to check if a user has input a valid date in a textbox, regardless of format? ``` function checkEnteredDate() { var inputDate = document.getElementById('txtDate'); //if statement to check for valid date var formatDate = new Date(inputDate.value); if (formatDate > TodayDate) { alert("You cannot select a date later than today."); inputDate.value = TodayDate.format("MM/dd/yyyy"); } } ```