RequiredValidator clientValidateAttribute - doesn't account for the use of 'when'

If using the ‘when’ property on a required validator to determine whether the attribute is required, the client side validation ignores that property and always returns required. Am I missing something there?


     * @inheritdoc


    public function clientValidateAttribute($model, $attribute, $view)


        $options = [];

        if ($this->requiredValue !== null) {

            $options['message'] = Yii::$app->getI18n()->format($this->message, [

                'requiredValue' => $this->requiredValue,

            ], Yii::$app->language);

            $options['requiredValue'] = $this->requiredValue;

        } else {

            $options['message'] = $this->message;


        if ($this->strict) {

            $options['strict'] = 1;


        $options['message'] = Yii::$app->getI18n()->format($options['message'], [

            'attribute' => $model->getAttributeLabel($attribute),

        ], Yii::$app->language);


        return 'yii.validation.required(value, messages, ' . json_encode($options, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . ');';



For example, I have the following rule on my model:

            [['gdate','level'], 'required', 'when'=>function($model) {

	            return !$model->has_children && $model->start_date;


When the client side validation is output, gdate and level inputs are always keyed as required.

What’s the best way to get around that, disable client side validation for that attribute and add custom script? Seems clunkier than necessary to do that, so I must be missing something…

Probably you have to write some code for "whenClient".$whenClient-detail

[edit] I’m afraid it may be sometimes impossible or very difficult to write the counter part of “when” in client side.

Thank you, that’s exactly what I was missing!!!

I’m very curious about what it would be like in the client side.

Would you please share your code?

Sure. I put the functions inline for simplicity. If it were a more complex form or there was any chance there would be multiple on the page, I’d not put it inline. That’s a different debate though ;)

[['gdate','level'], 'required', 'when'=>function($model) {

  /** @var MyApplication $model */

  return !$model->has_children && !$model->start_date;



      'function( attribute, value ){

           return $("#my-application-has_children").val()=="0" &&




(edited to make it more legible on the forum format/wrapping)

The values for the two parent attributes are both a limited set. I only want to validate these two attributes when both parents have had an option selected and the option selected was ‘No’ or ‘None’ (as the case may be)

Good illustration of the feature. Thanks. :)