How to specify a validation rule in Yii2 which will be greater than or less than of a specific number or value?

痞子三分冷 提交于 2019-12-07 01:26:03

问题


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'],


来源:https://stackoverflow.com/questions/29362069/how-to-specify-a-validation-rule-in-yii2-which-will-be-greater-than-or-less-than

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!