How to ensure end_date is after start_date?

Hello,

I am Having an issue using the compare validator to ensure that the start_date attribute must be a date before the end_date attribute.

In my rules I have followed the Docs as such:


    

public function rules() {

        return [

            ['end_date', 'compare', 'compareAttribute' => 'start_date', 'operator' => '>'],

        ];

    }



However, no matter what date I chose for end_date I always get the following validation error on the form:

"Position End Date must be greater than "Position Start Date".

Regardless of whether the end_date is greater, equal, or less than the start date, the validation rule behaves this way.

Any help is very much appreciated.

Thank you,

Oduncan

i know it only supports types number and string but if you use a before validate something like

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

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

it will always not validate saying it is greater than start date is greater than end date.

I tried doing a custom validator exact copy and paste from the docs but i couldn’t get it to fire either. I even had it only returning an error and it still wouldn’t show it.

I am also facing the exact same problem, any body out there will throw some light on it.

Thanks.

you can write custom validator to compare dates here you go




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.');

        }

    }

It’s more likely to be that if end date is before start date then it’s worth flagging as invalid. Code above should probably be:
if (!$this->hasErrors() && $end_date < $start_date) {