Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if user passes a valid date in javascript?

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");
            }
}
like image 595
MrM Avatar asked Jul 02 '09 12:07

MrM


People also ask

How do I know if a date is valid?

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.

How do you check if a string is a valid date in JavaScript?

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.

Is valid date format JavaScript?

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.


1 Answers

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

like image 187
Josh Avatar answered Sep 27 '22 17:09

Josh