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

3

8

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

Scalable answered 31/3, 2015 at 6:31 Comment(0)
F
13

It should be:

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

and

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

accordingly.

Read more in official docs.

Foliar answered 31/3, 2015 at 6:44 Comment(2)
Ehh)) You are faster)))Calcine
Hi @Foliar : How can we give message on this ? I gave ['x', 'compare', 'compareValue' => 100, 'operator' => '>=' , 'message'=>'Hi To all'],. But not working. Do you have any idea?Meave
U
3

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.

Ursula answered 4/8, 2018 at 5:57 Comment(0)
N
1

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'],
Nappe answered 15/2, 2019 at 10:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.