Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php date validation

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';` 
like image 686
Pablo Lopez Avatar asked Aug 19 '12 23:08

Pablo Lopez


People also ask

How do you check if a date is valid in PHP?

PHP | checkdate() Function The checkdate() function is a built-in function in PHP which checks the validity of the date passed in the arguments. It accepts the date in the format mm/dd/yyyy. The function returns a boolean value. It returns true if the date is a valid one, else it returns false.

What does date () do in PHP?

The date() function formats a local date and time, and returns the formatted date string.


1 Answers

You could use checkdate. For example, something like this:

$test_date = '03/22/2010'; $test_arr  = explode('/', $test_date); if (checkdate($test_arr[0], $test_arr[1], $test_arr[2])) {     // valid date ... } 

A more paranoid approach, that doesn't blindly believe the input:

$test_date = '03/22/2010'; $test_arr  = explode('/', $test_date); if (count($test_arr) == 3) {     if (checkdate($test_arr[0], $test_arr[1], $test_arr[2])) {         // valid date ...     } else {         // problem with dates ...     } } else {     // problem with input ... } 
like image 124
Nicolás Ozimica Avatar answered Sep 21 '22 13:09

Nicolás Ozimica