whenClient validation

I need help with whenClient validation

I have a status field and a value field. The validation I want to do is

  • must be client validation (e.g. users dont need to click submit for the validation to work)

  • when the value field is > 0, the status field (dropdown) must be APPROVED

Here is my validation code

['status', function ($attribute, $params) {            

    if ($this->$attribute != self::STATUS_APPROVED) {

        $this->addError($attribute, 'Status must be APPROVED because Value is not empty');


}, 'when' => function ($model, $attribute) {

    return $model->value > 0;

}, 'whenClient' => "function (attribute, value) {

        return ($('#value').val() > 0);


The validation only work on submit button is pressed. My guess is because I use custom validation code so the validation doesnot work for client validation.

Any idea how to make this work for client validation ?

In order to do client-side validation, the validator must implement "clientValidateAttribute()" method that returns the javascript to perform the client-side validation.


So, you have to write your own clientValidateAttribute(). Or, I would rather recommend you to consider using one of the built-in core validators, since many of them have that method already implemented.

For instance, how about using "compare" validator? http://www.yiiframework.com/doc-2.0/guide-tutorial-core-validators.html#compare

['status', 'compare', 'compareValue' => self::STATUS_APPROVED, 'operator' => '==',

    'message' => 'Status must be APPROVED because Value is not empty',

    'when' => function ($model, $attribute) {

        return $model->value > 0;


    'whenClient' => "function (attribute, value) {

        return ($('#value').val() > 0);



See also http://www.yiiframework.com/doc-2.0/guide-input-validation.html#implementing-client-side-validation

Hi Aluzio,

Can you try the number validator with min and max ?

Yii2 Number validator


Happy Coding…

thanks alot