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!'); } }
@Jim – I’m not sure why you have to change from “!==” to “!=” in the last if statement to make this function work. isDate() is checked with JSlint and tested in FireFox 3.5, Google Chrome 9 and Internet Explorer 8. Did you make any other modification in code and in which browser this problem occurs?
@dbunic I did make one modification to the code which I have found out caused the problem although I’m not sure why. I wanted to check for the format yyyy/mm/dd so I made the following change:
@Jim – You should add subtraction with zero to cast “day” and “year” variables to integer.
Or you can use parseInt:
If using the triple equals (or !== operator), the values must be equal in type as well. In your case you compared string with integer and that was false.
@dbunic Thanks! Didn’t realise what i’d done there but it makes sense.
i want javascript validation for From date n To date fields…….. can u help me as soon as possilble plzzzzzz
@Tejasvi ware – If you have two input boxes for date data type, isDate() function can be used for both fields. After user clicks on save button (or any other button to finish the input process) form validation should go straight after. Inside validate() function you will have to validate both dates – that’s nothing new – but you will have to check if first date precedes the second date. So, with all of the mentioned conditions, validate() function may look like this:
Hope this code snippet will give you some hints of how to check "From" and "To" input dates ...
Great site & great info – thx!
I’ve been looking all week for a good date validation routine that can work without using forms or any buttons. Would yours work on a different event? Everyone and their mother have it onSubmit with forms – Geez!!!
Thx,
KJ
@KJ – isDate() is a simple JavaScript function and can be called from any event handler you need. In this demo, date validation is called on button click. Please see HTML code of “Check the date” button.
@Vikramjit – Your solution contains much refined error messages then my isDate() function. It is helpful but price for that is amount of code and elegancy. Anyway, thank you for posting your version of date validation. Cheers!
Wow that’s a lot of code I just use:
@Scott – Yes, your code is short but it doesn’t verify if month have 30 or 31 day or if February has 28 or 29 days. That’s the reason why converting txtDate to milliseconds and returning it back. Returned date (from milliseconds) is compared to txtDate and if difference exists, then input date is wrong …
Hi dbunic
could you help in validation of a date where a user should not be able to select a date prior to 2 weeks of the todays date. Means a user can select a date for 2 weeks prior to todays date but it should not allow user to select date before those 2 weeks.
i have a datetime picker in my form where a user can click to select the date and a calender opens a date is selected.
@vijay – Here is code snippet to test if input date is in valid range:
User input should be verified before testing date range.
Only discuss that validation of date format. dont check if the date is correct
I don’t have experience with javascript. I’d like to know how can you perform a check on two or more text fields in one web page. Can you provide me with a working code? thanks.
@annse – Here is modification of checkDate() function to test two date fields on page. chechDate() can be called before form submit or any other event (like button click):
thanks Darko for taking the time to reply to my post. more success to you. cheers!
Hi , In popular sites i observed one thing , instead of entering date , they give on button. when we click on it one calender is opening. can u provide the code for that task.
@sanjay – JavaScript date picker is a bit complex code and it can’t fit in a few lines. Anyway, my goal was to show simple date validation in a case when user has option to manually input date. I’m sure there are plenty of good date pickers, so creation of a new one is not currently on my task list. ;)