How to specify a validation rule in Yii2 which wil

2019-04-28 02:06发布

问题:

I have a model with a validation rule like:

[['x'], 'integer'],
[['x'], 'unique'],

Now how can I add a rule like:

x < 100
or something like
x >= 100

回答1:

It should be:

['x', 'compare', 'compareValue' => 100, 'operator' => '<'],

and

['x', 'compare', 'compareValue' => 100, 'operator' => '>='],

accordingly.

Read more in official docs.



回答2:

You could also use the min attribute on number, or integer validators:

['age', 'integer', 'min' => 0],
['amount', 'number', 'min' => 0],

There is also a max option.



回答3:

Yii2 greater than validation :

field_to must be greater than "field_from".

Field 1 : field_from

Field 2 : field_to

[['field_to'], 'compare', 'when' => function($model) {
                        return $model->builtup_area != null;
                    }, 'whenClient' => "function (attribute, value){
                    return $('#form-field_from').val() != '';
                }", 'compareAttribute' => 'field_from', 'operator' => '>', 'type' => 'number'],