Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP DD/MM/YYYY Validation [duplicate]

apologies for probably a simple question, but i am new to PHP and Javascript.

I am creating a login validation in PHP that requires a registering user to input their date of birth in a DD/MM/YYYY Format, that returns an error message if the date is entered in any other format. I am unsure how to do this, other than using preg_match, however this doesnt seem to work...

variables:

$DOB = $_POST['DOB'];
$error_message = '';

The Date Validation Segment

elseif (!preg_match("/^(0?[1-9]|[12][0-9]|3[01])\/\.- \/\.- \d{2}$/", $DOB))
{
  $error_message = 'Invalid Date';
}

Error Display

  if ($error_message != '')
  {
    echo 'Error: '.$error_message.' <a href="javascript: history.back();">Go Back</a>.';
    echo '</body> </html>';
    exit;
  }
  else
  {
   echo'<p><strong>Form Submitted Successfully!</strong></p>';
  }

This is not a duplicate, i tried other threads and none of their solutions worked.

like image 478
Krono Avatar asked Aug 07 '15 06:08

Krono


1 Answers

You should use more than a regular expression. For example, you should not allow something like 31/02/2015, because there's no 31th in February!

I have a function that works well:

function isDate($string) {
    $matches = array();
    $pattern = '/^([0-9]{1,2})\\/([0-9]{1,2})\\/([0-9]{4})$/';
    if (!preg_match($pattern, $string, $matches)) return false;
    if (!checkdate($matches[2], $matches[1], $matches[3])) return false;
    return true;
}

It first uses preg_match to check for the formal validity of DD/MM/YYYY, grabbing DD, MM and YYYY portions into the $matches array. Then it check the validity of the date itself using the built-in PHP function checkdate.

You can use that in your code like:

if (!isDate($DOB)) {
    $error_message = 'Invalid Date';
}
like image 148
lorenzo-s Avatar answered Sep 22 '22 13:09

lorenzo-s