[AS2] Quick and easy Date Validation

isValidDate Function
Simply checks if a valid date has been entered and returns true or false.
There’s no need for a whole heap of conditional statements and string manipulation because the Date object will validate itself.

ARGUMENTS:
[COLOR=“Red”]day [/COLOR]- the day to check
[COLOR=“red”]month[/COLOR] - the month to check
[COLOR=“red”]year[/COLOR] - the year to check

RETURNS:
[COLOR=“red”]Boolean[/COLOR] - True if year, month, and day are valid; otherwise it returns False

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

Sample Use:

trace("Checking 31/3/2008: " + isValidDate(31, 3, 2008)); // true
trace("Checking 31/4/2008: " + isValidDate(31, 4, 2008)); // false
trace("Checking 30/2/2008: " + isValidDate(30, 2, 2008)); // false
trace("Checking 29/2/2007: " + isValidDate(29, 2, 2007)); // false
trace("Checking 29/2/2008: " + isValidDate(29, 2, 2008)); // true
trace("Checking 32/3/2008: " + isValidDate(32, 3, 2008)); // false
trace("Checking 31/13/2008: " + isValidDate(31, 13, 2008)); // false

If you still like manipulating strings, and 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])); // 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])); // false

Finally, the function can also 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) {

Nice man, useful for sure