5

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.

1
  • Should't browser do that for you if you use <input type="date">? Aug 7, 2015 at 6:42

3 Answers 3

16

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';
}
1
  • This worked perfectly! Thank you all for the help :D
    – Krono
    Aug 7, 2015 at 7:30
1

string_explode given string and then pass parts of it to

bool checkdate ( int $month , int $day , int $year )

unfortunately you cannot know if user posted month and day in your format if day is not greater than 12

1
  • people say that you should use client sided validation as sending data to server just for that is expensive yes! you should validate client side, but anyway you have to validate what server receives incase of some "funny" guy playing around
    – zakius
    Aug 7, 2015 at 6:49
1

You can do it like this in PHP:

$date=explode("/",$_POST['DOB']);
if(checkdate ($date[1] ,$date[0] ,$date[2]))
{
    echo "valid";
}
else 
{
    echo "invalid";
}

checkdate will only return true if the three value behind "/" is valid, so if there's no "/" its invalid, same as they put numbers in wrong order.

check manual http://php.net/manual/en/function.checkdate.php

Not the answer you're looking for? Browse other questions tagged or ask your own question.