Working with dates (and time, but time is not part of my post this time) can be very frustrating when it has to be validated, depending on how you need to validate.
Validating it for proper format is easy, a simple regular expression can validate a YYYY-MM-DD type of format (or any other):
re = /^\d{4}\-\d{2}\-\d{2}$/;
if(!date_string.match(re))
{
alert("not proper formatting");
}Pretty simple, right?OK, but what if you need to compare dates, such as making sure the start date is before the end date in some sort of a date range query? First, bust it up into pieces of year, month and day at the delimiter, which is usually a - or / or ., so, just split it on that, for starters.
var dt = date_string.split("-");
test_date = (new Date(dt[0], parseInt(dt[1]-1), dt[2]));
The last solution I will cover will be to determine if the entered date is actually a real date...think about somebody trying to pass in something like 2011-02-30...that would pass a simple formatting test, and within the range of most acceptable month and day ranges...so, with the function below, you pass in your date, in three variable, year, month and day, by splitting it as mentioned above, it will take those three, and then turn it into a JavaScript date object, then use JavaScript to get the year, month and day from that object...then compare the original year, month and day to the object derived year, month and day.
function isDateValid(year, month, day)
{
month = month - 1;
mSeconds = (new Date(year, month, day)).getTime();
objDate = new Date();
objDate.setTime(mSeconds);
if (objDate.getFullYear() != year || objDate.getMonth() != month || objDate.getDate() != day)
{
return false;
}
return true;
}
So, how does that work for ya?