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");
}
}
Given date in format date, month and year in integer. The task is to find whether the date is possible on not. Valid date should range from 1/1/1800 – 31/12/9999 the dates beyond these are invalid. These dates would not only contains range of year but also all the constraints related to a calendar date.
Using the Date. One way to check if a string is date string with JavaScript is to use the Date. parse method. Date. parse returns a timestamp in milliseconds if the string is a valid date.
mm/dd/yyyy or mm-dd-yyyy format. In the following examples, a JavaScript function is used to check a valid date format against a regular expression. Later we take each part of the string supplied by user (i.e. dd, mm and yyyy) and check whether dd is a valid date, mm is a valid month or yyyy is a valid year.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With