|
Author:
I needed to check a form field for proper dates prior to their submission to a database. The best way to do this is to use Perl's RegEx or Regular Expressions.
You should be able to plug everything between the two /'s into a PHP script and test it (the slashes are not part of the expression, they are the delimiters in Perl; also, I believe, in PHP).
/((^0?[1-9]|^1[0-2])\/(0?[1-9]|[1-2][0-9]|3[0-1])\/(19|20)?[0-9][0-9]\z)| ((January|February|March|April|May|June|July|August|September|October|November|December) ([1-2][0-9]|3[0-1]|0?[1-9]), (19|20)[0-9][0-9]\z)/
This regex works on all dates from January 1, 1900 through December 31, 2099. It will validate the following formats:
mm/dd/yy
mm/dd/yyyy
Month dd, yyyy
For both mm's and dd's, leading zeros are optional. It will take any combination of 03/03/52, 3/3/52, 03/3/52, etc.
There can currently be only one space in each spot of the third format. For instance, if there were two spaces between Month and dd, the string would fail to validate. This can be changed by adding a + sign after the spaces in the regex, like this:
/((^0?[1-9]|^1[0-2])\/(0?[1-9]|[1-2][0-9]|3[0-1])\/(19|20)?[0-9][0-9]\z)| ((January|February|March|April|May|June|July|August|September|October|November |December) +([1-2][0-9]|3[0-1]|0?[1-9]), +(19|20)?[0-9][0-9]\z)/
This will allow one or many spaces.
If you run the Perl script (see below), you can execute the script and pass in the date as a command line variable, like this:
$ perl datechck.pl 03/30/52
if($ARGV[0] =~ /((^0?[1-9]|^1[0-2])\/(0?[1-9]|[1-2][0-9]|3[0-1])\/(19|20)?
[0-9][0-9]\z)|((January|February|March|April|May|June|July|August|September
|October|November|December) ([1-2][0-9]|3[0-1]|0?[1-9]), (19|20)?[0-9][0-9]\z)/)
{
print "Valid Date.\n$&\n";
}
else {
print "Invalid format.\n$2\n";
}