bgx:components logo
© 2004 -2005
Bernhard Gaul



Basic Flash Date Validation

The code below shows how to validate whether a string represents a valid date in the format "dd/mm/yyyy". The easy part is to split the string into its parts and then check if the parts represent indeed numbers in certain ranges.

I guess the trickier bit is to find out that e.g. "31/4/2004" or "29/2/2003" are not valid dates. Flash (or JavaScript for that matter) do indeed recognize a date like 31/2/2003, equaling however the 31st February with the 3rd March. In the same way the 50th April would be the same as the 20th May.

The trick I used below is first creating a date object with the parts controlled as valid and then checking if the month that Flash returns for the object is the same as that the user entered. If they don't match the date is invalid.

The code

var isValid = validateDate("31/2/2004");//will return false
			
function validateDate(dateString)
{
	if (dateString.indexOf("/") == -1) return false;
	var dateParts = dateString.split("/");
	if (dateParts.length != 3) return false;
	//basic check for numbers
	for (var i = 0; i < dateParts.length; i++)
	{
		if (isNaN(dateParts[i])) return false;
	}
	//check the individual parts
	if(Number(dateParts[0]) < 1 || Number(dateParts[0]) > 31 ) return false;
	if (Number(dateParts[1]) < 1 || Number(dateParts[1]) > 12 ) return false;
	if (Number(dateParts[2]) < 1000 || Number(dateParts[2]) > 9999 ) return false;
	
	var day = Number(dateParts[0]);
	var month = Number(dateParts[1]) - 1; //months are 0 based in Flash
	var year = Number(dateParts[2]);
	//create date
	var date = new Date (year, month, day); 
	//check for wrong days in month, e.g. 31 April or 30 February
	//Flash accepts something like date = new Date(2003,1,31); which in our
	//case the user would have entered as "31/2/2003" and would be invalid.
	//Flash in fact treats this date as 3/3/2003 (3 days after the valid 28 Feb)
	//therefore we can check for the month of the date object which will be 
	//different from the month we entered if the date doesn't exist
	if (date.getMonth() != month) return false;
	//finally - should be valid
	return true;
}