Aleksej_Shherbak
Aleksej_Shherbak

Reputation: 3068

How to validate date field for a model (Yii2)

Could anybody give me a nice example of validation a date field?

I have the following rules validation method:

    public function rules()
    {
        return [
            [['rewards_date_from', 'rewards_date_to'], 'date', 'dateFormat' => 'Y-m-d'], 

...

'rewards_date_from', 'rewards_date_to' - both fields have date type with format Y-m-d.

But this rules are wrong. Yii throws me the following exception:

Setting unknown property: yii\validators\DateValidator::dateFormat

Ok, I'm trying to validate it like:

    public function rules()
    {
        return [
            [['rewards_date_from', 'rewards_date_to'], 'date'], 

...

And I have the model errors: enter image description here

The messages mean: "Wrong format of Rewards date from" and the same for rewards_date_to field.

My input data is:

enter image description here

and the same for rewards_date_from field

Upvotes: 0

Views: 823

Answers (1)

Serghei Leonenco
Serghei Leonenco

Reputation: 3507

As documentation says, Class yii\validators\DateValidator, you must use format property to validate date field.

Try this:

public function rules()
{
    return [
       [['rewards_date_from', 'rewards_date_to'], 'date', 'format' => 'php:Y-m-d'],
...

Upvotes: 2

Related Questions