R
R
Roma Antonyuk2017-06-06 14:56:14
Yii
Roma Antonyuk, 2017-06-06 14:56:14

Validation via "each" in yii2?

validation does not work through each, the rules
field
public $child_age = [];

public function rules()
    {
        return [
            ['child_age', 'each', 'rule' => ['integer']],
            ['child_age', 'each', 'rule' => ['compare', 'compareValue' => 2, 'operator' => '>=']]
        ];
    }

and in view
<div class="number-control">
                                    <?= $form->field($model, 'child_age[]', [
                                        'template' => '{input}{error}'.Html::button('', ['class' => 'minus']).Html::button('', ['class' => 'plus'])
                                    ])->input('text', ['value' => 6])->label(false) ?>
                                </div>

what is wrong here? I don't understand

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Maxim Timofeev, 2017-06-06
@webinar

everything looks right, maybe it's not the problem?

D
davidnum95, 2017-06-06
@davidnum95

Try adding the skipOnEmpty parameter to the validator. Like this:

public function rules()
    {
        return [
            ['child_age', 'each', 'rule' => ['integer'], 'skipOnEmpty' => false],
            ['child_age', 'each', 'rule' => ['compare', 'compareValue' => 2, 'operator' => '>='], 'skipOnEmpty' => false]
        ];
    }

M
Maxim Fedorov, 2017-06-07
@qonand

It is unlikely that the validation does not work if everything is done correctly. Validation may not work only in the following cases:
1. You do not load the attribute data from the request into the model (it would not hurt to show the controller where this happens)
2. You have client-side validation or Ajax validation on other fields before submitting the form to the server, accordingly each-validation does not work.
It would not hurt that you showed the complete code of the form.
In general, judging by the code, you are reinventing the wheel. To solve your problem, it is easier to use a ready-made solution, for example this

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question