Kiryl Lapchynski
Kiryl Lapchynski

Reputation: 95

can't solve 'date' validation with 'max', 'min' properties Yii2

I can't understand - function returning string (verified by var_dump()):

['userBirthDate', 'date', 'format' => 'yyyy-MM-dd', 
'max' => function() {
    $date = new DateTime();
    date_sub($date, date_interval_create_from_date_string('12 years'));
    $maxDate = date_format($date, 'Y-m-d');
    return $maxDate;
},
'min' => function() {
    $date = new DateTime();
    date_sub($date, date_interval_create_from_date_string('100 years'));
    $minDate = date_format($date, 'Y-m-d');
    return $minDate;
}

],

but I have the mistake: "Object of class Closure could not be converted to string".

mistake code

Upvotes: 3

Views: 2502

Answers (1)

Joe Miller
Joe Miller

Reputation: 3893

The validators max and min can only accept a number, not an anonymous function, that's why you are getting the error.

Try this code, which creates a new validator called validateUserBirthDate, as well as using the existing date validator.

[
    ['userBirthDate'], 
    'validateUserBirthDate'
],
[
    ['userBirthDate'],
    'date', 'format' =>  'format' => 'yyyy-MM-dd'
]

then in your model add a custom validator;

public function validateUserBirthDate($attribute, $params) {
$date = new \DateTime();
date_sub($date, date_interval_create_from_date_string('12 years'));
$minAgeDate = date_format($date, 'Y-m-d');
date_sub($date, date_interval_create_from_date_string('100 years'));
$maxAgeDate = date_format($date, 'Y-m-d');
    if ($this->$attribute > $minAgeDate) {
        $this->addError($attribute, 'Date is too small.');
    } elseif ($this->$attribute < $maxAgeDate) {
        $this->addError($attribute, 'Date is to big.');
    }}

Upvotes: 1

Related Questions