Yii2 compareValidator when

530 views Asked by At

During user input validation I would like to compare an attribute with a value.

I have this code:

['ao_id', 'compare', 'when' => function($model) {
            return $model->lqp_id == 24 || $model->lqp_id == 26 || $model->lqp_id == 46;
        }, 'compareValue' => 50],

It works (however only when 'enableClientValidation' => false), but is it possible, to show rather the name of the foreign attribute somehow? Because it doesn't help much if the user is getting an error message that outer surface (ao_id) must be 50. Nobody has a clue what does it mean, because in the dropdown you see only the names and not the ids. Many thanks!

2

There are 2 answers

1
Bizley On BEST ANSWER

Add message key where you define your own message that will be displayed instead of default one.

2
deacs On

First of all, if you want your conditional validation to work on the client-side too (when enableClientValidation=>true), then add the whenClient property which contains the javascript code that will do the validation.

Second, you can use the message property to specify a custom validation error.

[
    'ao_id', 
    'compare', 
    'when' => function ($model) {
        return $model->lqp_id == 24 || $model->lqp_id == 26 || $model->lqp_id == 46;
    }, 
    'whenClient' => "function (attribute, value) {
        return $('#lqp_id').val() == '24' || $('#lqp_id').val() == '26' || $('#lqp_id').val() == '46';
    }", 
    'compareValue' => 50, 
    'message'=>'ao_id must be 50 when lqp_id is 24, 26 or 46'
]

Attention: be sure to check and change the id of the input field $('#lqp_id') as this is most likely different to my example.