Search code examples
phpvalidationrequireddate

PHP Validate required field + age validation in one function


I have a registration form with a required date of birth field.

    <tr>
      <td><span class="required">*</span> <?php echo $entry_dob; ?></td>
      <td><input type="text" id="dob" name="dob" value="<?php echo $dob; ?>"   /><p id="age"></p>
        <?php if ($error_dob) { ?>
        <span class="error"><?php echo $error_dob; ?></span>
        <?php } ?>

So in my php controller file [ I am using a software coded in MVC], I Have the following the following function to make the field required:

 if ((strlen(utf8_decode($this->request->post['dob'])) < 3) || (strlen(utf8_decode($this->request->post['dob'])) > 32)) {
        $this->error['dob'] = $this->language->get('error_dob');
    }

I also need to validate if the user is a least 19 years old. If he/she is not, an error will be displayed, I am using the following function in the same php controller file to achieve this:

$allowed_age = 19;
$bdate = strtotime($_REQUEST['dob']);
$age = (time()-$bdate)/31536000;
if($age < $allowed_age) {
 $this->error['dob'] = $this->language->get('error_dob');
}

And I have tested it and it seems to be working properly. However, I was wondering how can I validate the two things at once. I mean, validate if the user has input the dob, and if the age is older than 19.

I am not an expert, so if you know a better way to achieve this, please share it.

Best Regards,

Codekmarv


Solution

  • use this to get the age

    $age = floor( (strtotime(date('Y-m-d')) - strtotime($this->request->post['dob'])) / 31556926);
    

    and after that take $age value and just check it in if condition

    if (((strlen(utf8_decode($this->request->post['dob'])) < 3) || (strlen(utf8_decode($this->request->post['dob'])) > 32)) 
    && $age < 19) {
        $this->error['dob'] = $this->language->get('error_dob');
    }
    

    It will check for user has inputed a value and age is greater than 19.

    You have to use && operator to check multiple conditions.