JavaScript date validation can be done in many ways like month range testing, day range testing (depending on number of days in the month) and so on. Here is shown much simpler solution. Take day, month and year from input string to create JavaScript Date object. Compare input day, month and year with day, month and year extracted from the Date() object. If they aren’t the same then the input date is not valid.
Please try how date validation works (month and day can contain leading zeros):
Enter date (m/d/yyyy): |
Function is checked with JSLint (JavaScript syntax checker and validator).
function isDate(txtDate, separator) { var aoDate, // needed for creating array and object ms, // date in milliseconds month, day, year; // (integer) month, day and year // if separator is not defined then set '/' if (separator === undefined) { separator = '/'; } // split input date to month, day and year aoDate = txtDate.split(separator); // array length should be exactly 3 (no more no less) if (aoDate.length !== 3) { return false; } // define month, day and year from array (expected format is m/d/yyyy) // subtraction will cast variables to integer implicitly month = aoDate[0] - 1; // because months in JS start from 0 day = aoDate[1] - 0; year = aoDate[2] - 0; // test year range if (year < 1000 || year > 3000) { return false; } // convert input date to milliseconds ms = (new Date(year, month, day)).getTime(); // initialize Date() object from milliseconds (reuse aoDate variable) aoDate = new Date(); aoDate.setTime(ms); // compare input date and parts from Date() object // if difference exists then input date is not valid if (aoDate.getFullYear() !== year || aoDate.getMonth() !== month || aoDate.getDate() !== day) { return false; } // date is OK, return true return true; }
isDate() function has an optional second parameter to define date separator. Default value is “/”. In case of other date format (like “d/m/yyyy”) it’s only needed to change the order of day, month and year variables after splitting the input string. The main intention was to keep this function short and simple so support for other date formats has to be done manually. And finally, see how to use date validation. checkDate() function is called on button click “Check the date” above the source code:
function checkDate(){ // define date string to test var txtDate = document.getElementById('txtDate').value; // check date and print message if (isDate(txtDate)) { alert('OK'); } else { alert('Invalid date format!'); } }
Nice Script!
Thanks, one of the most elegant scripts I’ve seen that checks the date …
Nice work!! Cleverly done.
good script
A very good one, thanks, you spared me some work hours :)
thank’s a lot!a great great solution
This is a great script – simple solution and nice comments. Thanks for sharing!
I made a simple edit that I wanted to share in case it helps anyone. By using the split() function to grab the date pieces (rather than specific indices) you can support single digit months and days.
Here is the updated code (replacing lines 7 – 20 above):
// date length should be 8-10 characters – no more, no less
if ((txtDate.length 10)) return false;
// extract day, month and year from the txtDate string
var dateArray = txtDate.split(“/”);
if (dateArray.length !== 3) return false; // should only have 2 ‘/’ chars
// subtraction will cast variables to integer implicitly
var month = dateArray[0] – 1; // months in JS start with 0
var day = dateArray[1] – 0;
var year = dateArray[2] – 0;
// test year range
….
Sorry – left a few mistakes in the last post.
1) New form allows 8-10 characters, so length test should read:
if ((txtDate.length 10)) return false;
2) Converting a sting to a number using subtraction will remove any trailing decimals (e.g. “12.”) or zero value decimals (e.g. “12.0”). Depending on how you’re sending the date information to the server, any decimals in the string may cause issues. Therefore, you can check for any “.” characters and fail if they exist.
if (txtDate.indexOf(“.”) !== -1) return false;
Its realy a nice script i m searching 4 the date validation 4m past 2 days.
Now i got it want i want.
Thanka a lot.
how can we validate a date according to the system specific culture.imean to say the scipt shud check the dates in UK and US formats either with’-‘ or ‘.’ or ‘/’. iam able to get the system format used and i wanna validate the date on that format please advice
First, I would like to thank you the author who posted this script. It is really useful.
Secondly, I like to thanks Richard’s method for allow “single digit month”, even though there was some typo in your code, which will not going to work.
Here is the modification and hope it helps someone wants to allow single digit month and day also.
Replace this below
—————————————————-
// date length should be 10 characters – no more, no less
if (txtDate.length != 10) return false;
// extract day, month and year from the txtDate string
// expected format is mm/dd/yyyy
// subtraction will cast variables to integer implicitly
var day = txtDate.substring(3,5) – 0;
var month = txtDate.substring(0,2) – 1; // because months in JS start with 0
var year = txtDate.substring(6,10) – 0;
// third and sixth character should be /
if (txtDate.substring(2,3) != ‘/’) return false;
if (txtDate.substring(5,6) != ‘/’) return false;
—————————————————-
Replace with this:
—————————————————-
// date length should between 8 to 10 characters
alert(“length: ” + txtDate.length)
if (txtDate.length 10) return false;
var dateArray = txtDate.split(“/”);
alert(“Array: ” + dateArray.length);
if (dateArray.length != 3) return false; // shoud only have 2 “/” chars
// subtraction will cast variabls to integer implicitly
var month = dateArray[0] – 1; //Months in JS start with 0
var day = dateArray[1] – 0; // Day
var year = dateArray[2] – 0; // Year
—————————————————-
@Richard – Thanks!
@milacay – Thank you for improving date validation code with single digit month and day. Date validation script will show the trick how to initialize Date() object from string, return string back and compare values. If values doesn’t match, then something is wrong with input date. I tried to make script short so it has room for improvement like yours. Thank you once again.
10/31/2010
Is this a valid date? Try inputting the same…! :-)
@santosh – Yes, this is valid date. After clicking on “Check this date” for 10/31/2010 script responses with “OK”. There should not be any problem. Can you give me a little bit more details about your case.
Thanks!
I’m sorry, for giving invalid entry…! I wanted to do with dd/mm/yy not mm/dd/yyyy…! Can you help me out with this?
@santosh – This demo works with mm/dd/yyyy format, but you are free to modify/customize date validation for your needs. Instead of substring definitions:
You can modify lines for dd/mm/yy format:
Multiply with 1 will cast to numeric value. If you leave only “+ 2000” then you will get string concatenation. And don’t forget:
at the script beginning.
thank you for help in code for validation of date in javascript
if (!isDate(fobj.mnth.value+’-‘+fobj.dt.value+’-‘+fobj.yr.value)) {
alert(‘Invalid date’);
return false;
}
return true;
As I can see from your example, you have separate input fields for date input. After concatenation you called isDate() function for validation. My demo expects mm/dd/yyyy date format and ‘/’ as separator. Instead of ‘-‘ for concatenation please use ‘/’ or just wipe out or change separator checker in isDate() validator (lines after comment “third and sixth character should be ‘/'”)
Thanks for the script. It was clean and efficient. For my project I needed something like accepting DDMMYYYY and MMDDYYYY and separators like “.” “-” “/” “\”. Concatenate and display 0 if single digit is entered for day/month. I modified the script, find the script below. Greatly appreciated if anyone can make this better
Not sure if anyone mentioned this but in order for it to work I had to change the triple equals/not equals operators in the last if statement to: