JavaScript date validation can be done in many ways, like month range testing, then day range testing (depend on month) and so on. I suggest simpler solution. Take day, month and year from string to create a Date object. Compare day, month and year with day, month and year extracted from the Date() object. If they aren't the same, than the input date is not valid.
Please try how date validation works:
| Enter date (mm/dd/yyyy): |
Function is checked with JSLint (JavaScript syntax checker and validator).
function isDate(txtDate) {
var objDate, // date object initialized from the txtDate string
mSeconds, // txtDate in milliseconds
day, // day
month, // month
year; // year
// date length should be 10 characters (no more no less)
if (txtDate.length !== 10) {
return false;
}
// third and sixth character should be '/'
if (txtDate.substring(2, 3) !== '/' || txtDate.substring(5, 6) !== '/') {
return false;
}
// extract month, day and year from the txtDate (expected format is mm/dd/yyyy)
// subtraction will cast variables to integer implicitly (needed
// for !== comparing)
month = txtDate.substring(0, 2) - 1; // because months in JS start from 0
day = txtDate.substring(3, 5) - 0;
year = txtDate.substring(6, 10) - 0;
// test year range
if (year < 1000 || year > 3000) {
return false;
}
// convert txtDate to milliseconds
mSeconds = (new Date(year, month, day)).getTime();
// initialize Date() object from calculated milliseconds
objDate = new Date();
objDate.setTime(mSeconds);
// compare input date and parts from Date() object
// if difference exists then date isn't valid
if (objDate.getFullYear() !== year ||
objDate.getMonth() !== month ||
objDate.getDate() !== day) {
return false;
}
// otherwise return true
return true;
}
And finally, see how to use date validation function. checkDate() is called on button click.
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!');
}
}

Hi
If we pass date string to date object and check if there is any exception and catch that exception, do you think it will work.
@Gajendra - That might work, but I'm not sure if Date object will throw an exeption for incorrect input. Here is example:
var mydate = Date('qwerty'); console.log(mydate);Instead of exception JavaScript will print current date:
Was it your idea or did you have something else in mind? Any other opinion is more then welcome.
I will appreciate if you can provide the full code and script for this example here.
@gondai - The full code for testing date is already shown. In onclick event listener of Check the date button checkDate() function is called. You can see how alert is displayed depending on return value from isDate() function. The nice part of Web is that nothing can be hidden. You can always peek under the hood and see the source of any component of HTML page (except Flash). Yes, scripts can be minimized and hard to read, but there is option to un-minimize and beautify the code.
Thank you so much for this code. With slight modifications I have been able to validate YYYY-MM-DD
Hi. Thanks for the great code and discussion. What I am searching for is a way to access a stated MinDate and MaxDate from our forms (different for each form) and use them in the JavaScript to complete the validation. (I'm using ASPX)
Here is a snippet of my code:
I can get into the validation code and do the validating on the client. I just can't find a way to access and use the min and max dates within that same JavaScript.
Thanks in advance!
@Will - you need to compare dates. Here is small JS code for a such function:
// compare dates and return number of days between function cmpDate(dat1, dat2) { var day = 1000 * 60 * 60 * 24, // milliseconds in one day mSec1, mSec2; // milliseconds for dat1 and dat2 // valudate dates if (!isDate(dat1) || !isDate(dat2)) { alert("cmpDate: Input parameters are not dates!"); return 0; } // prepare milliseconds for dat1 and dat2 mSec1 = (new Date(dat1.substring(6, 10), dat1.substring(0, 2) - 1, dat1.substring(3, 5))).getTime(); mSec2 = (new Date(dat2.substring(6, 10), dat2.substring(0, 2) - 1, dat2.substring(3, 5))).getTime(); // return number of days (positive or negative) return Math.ceil((mSec2 - mSec1) / day); }... and example of how to use it:
var dat1 = '01/23/2011', dat2 = '01/24/2011'; if (cmpDate(dat1, dat2) > 0) { alert('Dat1 is prior dat2!'); } else if (cmpDate(dat1, dat2) < 0) { alert('Dat1 is after dat2!'); } else { alert('Dat1 and dat2 are the same!'); }Hope this will help.
@dbunic - Thanks for the reply. Unfortunately my code snippet did not get included, so I was not clear in my question.
I'll try to include the code. Here is part of my form:
Later in the validation function
function DateValidatorEvaluateIsValid(val) { var control = document.getElementById(val.controltovalidate);I can check for a valid date format but do not know how to get the MinDate and MaxDate from the form to test in the function.
@dbunic Say, how do I include blocks of code here? I suspect I need to insert some special code or something. Thanks!
@Will - I changed instructions below comment. Now you can see HTML elements that can be used in comment (any other HTML tag will be stripped). Anyway, before posting JS code or HTML you can (or should) replace every occurence of:
... (just make search and replace before posting). After your comment is posted, I will place it inside box to be easier for reading. Thanks!
@dbunic
Thanks - I'll try again.
What I am searching for is a way to access a stated MinDate and MaxDate from our forms (different for each form) and use them in the JavaScript to complete the validation. Here is a snippet of my code in ASPX:
<MyStuff:DateTextBox ID="adate" runat="Server" Pattern="MM/dd/yyyy" /> <MyStuff:DateValidator ID="dateValidator" runat="Server" ControlToValidate="adate" ErrorMessage="Please enter a date in the following format {0} that falls between {1} and {2}." MinDate="1/1/1940" MaxDate="12/31/2011" />Later in my JavaScript validation function (here I just show the header)
function DateValidatorEvaluateIsValid(val) { var control = document.getElementById(val.controltovalidate);I can get into the validation code and do the validating on the client(i.e. confirm it is a date, etc). I just can't find a way to access and use the min and max dates within that same JavaScript. If I hard code a MaxDate and Mindate I can use them to validate. So, the function will work as desired when I can access the Min and Max Dates from the form. Any insight/help would be greatly appreciated!
@Will - Maybe you can prepare min/max date with aspx logic as hidden parameters within each form like this:
After date range is on the client side it easy to access and use for validation. Here is how to access dates from first form (second form will have index 1):
// set form reference and minDate/maxDate var frm = document.forms[0], minDate = frm.minDate.value, maxDate = frm.maxDate.value; // display minDate and maxDate alert(minDate + ' ' + maxDate);Hope this hint will give you a direction of how to use date ranges for validation. If you'll have any other question, please don't hesitate to comment.
@dbunic That is a creative solution. I was expecting some way to access the MinDate and MaxDate on the MyStuff:DateValidator line from within the JavaScript function. But this works too.
Thanks for your help!