I am using yii2, I have three fields num1,num2,num3. I want to add validation, num2 input should be greater than num1 input, so I am using compare rule. Here is the code
return [
[['num1', 'num2', 'num3'], 'required'],
[['num1', 'num2', 'num3'], 'integer', 'min' => self::MIN_SIZE, 'max' => self::MAX_SIZE],
['num2', 'compare', 'compareAttribute' => 'num1', 'operator' => '>'],
];
}
Issue: It works if I add 8,9,10 in the inputs but fails If I add 8,10,11 in the inputs. I have tried adding input type as number.
CodePudding user response:
The operands are compared as strings by default in yii\validators\CompareValidator
. That's why '10'
is considered less than '8'
.
You need to set CompareValidator::$type
property to compare operands as numbers.
Your rule should look like this:
[
'num2',
'compare',
'compareAttribute' => 'num1',
'operator' => '>',
'type' => \yii\validators\CompareValidator::TYPE_NUMBER
]