Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 508
Kiryl Lapchynski Avatar asked Dec 15 '25 19:12

Kiryl Lapchynski


1 Answers

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.');
    }}
like image 151
Joe Miller Avatar answered Dec 18 '25 22:12

Joe Miller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!