Age validate minimum age 18years


(Nishitadoval) #1

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.


(Softark) #2

Hi @Nishitadoval, welcome to the forum.

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


(Nishitadoval) #3

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


(Softark) #4

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:


(Nishitadoval) #5

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


(Softark) #6

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'],
        ...
    ];

(Nishitadoval) #7

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.


(Softark) #8

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