Age validate minimum age 18years

How can i validate age to be minimum 18 years?
This is my D.O.B field in form.php file

<?= $form->field($model, 'empdob')->widget(DatePicker::classname(), [ 'options' => ['placeholder' => 'Enter birth date ...'], 'pluginOptions' => [ 'autoclose'=>true, 'format' => 'yyyy-mm-dd' ]]); ?>

I tried using this in my model class but it doesnt work
array(‘empdob’, ‘ext.validators.age.EAgeValidator’,
‘minAge’=>18,
‘maxAge’=>120,
‘allowEmpty’=>false
),

Please help.

Hi @Nishitadoval, welcome to the forum.

Unfortunately AgeValidator is an extension for Yii 1.1 and it will not work with Yii 2.

So is there any other way of doing it and how?

Something like the following should work:

public function rules()
{
    // today
    $date = new DateTime();
    // 18 years ago
    $date->sub(new DateInterval('P18Y'));
    // maximum birthday
    $max = $date->format('Y-m-d');

    return [
        ['empdob', 'date', 'max' => $max, 'tooBig' => 'Must be 18 years old or older'],
        ...
    ];
}

Please check the following documents:

Class ‘app\models\DateTime’ not found

it is showing this error

Edited : Ok i imported DateTime and DateInterval for the above error
but now it shows this error

Invalid max date value: 2001-11-29

Ah, probably we have to set ‘format’ attribute.

    return [
        ['empdob', 'date', 'format' => 'php:Y-m-d', 'max' => $max, 'tooBig' => 'Must be 18 years old or older'],
        ...
    ];

Hey! Thank you for your help and time :slight_smile: and sorry i couldn’t check it earlier as it was the weekend.
So, I put the Format as said above but nothing changed , it is not working.

Well, it works for me. How does it fail?

It doesn’t show any error as such and accepts the value, so not able to understand what is the problem. I also printed the $max value , it shows correct value like 2001-12-06.