Kumar V
Kumar V

Reputation: 8830

Yii2: Dynamic max value validation rules

How to add customized validation for a field in yii2.? Textbox value should not exceed a table field values from current model. Is there any way to add new rule from controller?

Ex: $model->f1 should be lessthan or equal to $model->f2.

I got some points with dynamicmodel. But i have only one field to check.

it should work on client side also.

is there anyway to add custom rule from controller or in activeform?

Thanks.

Upvotes: 0

Views: 533

Answers (2)

yetanotherse
yetanotherse

Reputation: 500

Add this to your validation rules in model to ensure f1 value is <= f2.

[
  // other validation rules
  ['f1', 'compare', 'compareAttribute' => 'f2', 'operator' => '<='],
]

Upvotes: 1

Double H
Double H

Reputation: 4160

You Can use CompareValidator compareValue property as :-

 public function rules()
{
    return [
       // Your Validation rules as
        [
            'f2' ,
            'compare' ,
            'compareValue' => ArrayHelper::getValue($this , ['oldAttributes' ,'f1']),
            'operator' => '<=',
        ]
    ];
}

Model f1 value which is saved in database must be greater than f2 filled by user

Upvotes: 1

Related Questions