Im trying to to set up a php date validation (MM/DD/YYYY) but I'm having issues. Here is a sample of what I got:
$date_regex = '%\A(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d\z%';
$test_date = '03/22/2010';
if (preg_match($date_regex, $test_date,$_POST['birthday']) ==true) {
$errors[] = 'user name most have no spaces';`
REGEX should be a last resort. PHP has a few functions that will validate for you. In your case, checkdate is the best option. http://php.net/manual/en/function.checkdate.php
Though
checkdate
is good, this seems much concise function to validate and also you can give formats. [Source]function was copied from this answer or php.net
The extra
->format()
is needed for cases where the date is invalid butcreateFromFormat
still manages to create a DateTime object. For example:Use it:
Nicolas solution is best. If you want in regex,
try this,
this will validate for, 01/01/1900 through 12/31/2099 Matches invalid dates such as February 31st Accepts dashes, spaces, forward slashes and dots as date separators
Try This
this regular expression valid for :
Remember that this will be cover all case of date and date time with (-) character
You can use some methods of the
DateTime
class, which might be handy; namely,DateTime::createFromFormat()
in conjunction withDateTime::getLastErrors()
.This even allows us to see what actually caused the date parsing warnings/errors (look at the
warnings
anderrors
arrays in$date_errors
).