Wednesday, July 30, 2008

Validating Dates in Flash

Having seen a plethora of functions that attempt to validate dates in Flash, almost all of them involving various methods of splicing strings and a whole heap of conditional if statements to check for leap years, month lengths, etc., I thought it would probably be a lot simpler to let the Date Object itself do the checking:

function isValidDate(day, month, year):Boolean {
var d:Date = new Date(year, --month, day);
return d.getDate() == day && d.getMonth() == month && d.getFullYear() == year;
}

As you can see, the function accepts three arguments; the day, month, and year; and it returns a boolean true or false depending on whether the date is valid or not.

Using the function is simplicity itself:

trace("Checking 31/3/2008: " + isValidDate(31, 3, 2008)); // returns true
trace("Checking 31/4/2008: " + isValidDate(31, 4, 2008)); // returns false

To validate dates that are entered in a different format, e.g. for US-style dates (mm/dd/yyyy) just swap the order of the function arguments:

function isValidDate(month, day, year) {
}

If you still want to validate the correct use of date delimiters, you can do so quite easily by first splitting the date into an array and then checking against each index. The function will continue to return true or false, as this example demonstrates:

var date_str:String = "28/2/2008";
var date_arr:Array = date_str.split("/");
trace(isValidDate(date_arr[0],date_arr[1],date_arr[2]));
// returns true
var date_str:String = "28-2-2008";
var date_arr:Array = date_str.split("/");
trace(isValidDate(date_arr[0],date_arr[1],date_arr[2]));
// returns false

No comments: