Compare Validation on Date

I am having two models namely Patient Admission having two columns such as admission_date and discharge_date and another model daily_ward_entry having a date field say just date both models are related by ipd_patient_id

Now What I want is to create one or two validators, so that I can restrict the date entry in daily_ward_entry between admission_date and discharge_date

I had a look at the compare validator, but I can’t make out, how to replace the value to be compared with attribute from another model with relation.

I have tried following variations, but it always throwing error:

Variation one


[$this->discharge_date, 'compare', 'compareValue' => $this->admission_date, 'operator' => '>='],

error - Unknown Property – yii\base\UnknownPropertyException

Variation two


['discharge_date', 'compare', 'compareValue' => 'admission_date', 'operator' => '>='],

error - Discharge Date must be greater than or equal to "admission_date". This error is generated irrespective of date is lower or greater

variation three


[strtotime($this->discharge_date), 'compare', 'compareValue' =>strtotime($this->admission_date), 'operator' => '>='],

error - Unknown Property – yii\base\UnknownPropertyException

I need some direction and help. Thanks.

You need to use a custom validation rule. “compare” validation does not accept dates it only accepts string or number (see docs here). I fought with this for awhile one day. I tried to convert the dates to numbers and it wouldn’t validate it then. The only thing i could get to work was a custom validator.

Below is from another post credit goes to alirz23. This doesn’t do what you need it to do but it will give you an idea on how to do it. I didn’t have enough info to answer you question completely. I’d need to know what model it is being used when creating the item.


public function rules()

    {

        return [

//...

            ['end_date', 'compareDates'],

//...

        ];

    }


    public function compareDates()

    {

        $end_date = strtotime($this->end_date);

        $start_date = strtotime($this->start_date);

        if (!$this->hasErrors() && $end_date > $start_date) {

            $this->addError('end_date', 'End date is not valid.');

        }

    }