| 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");
function validateDate(dateString)
{
if (dateString.indexOf("/") == -1) return false;
var dateParts = dateString.split("/");
if (dateParts.length != 3) return false;
for (var i = 0; i < dateParts.length; i++)
{
if (isNaN(dateParts[i])) return false;
}
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;
var year = Number(dateParts[2]);
var date = new Date (year, month, day);
if (date.getMonth() != month) return false;
return true;
}
|