Set length on when required Yii2 rules

1.7k Views Asked by At
 [['shortcode'],'string', 'length' => [8, 11]],// first
 ['shortcode','required', // second
                'when' => function($model) {
                  // code here
                },
 ],

How can I combined my rules length only on if I set it to required ? Thanks in advance.

For now, Im always ending up checking for min length.

1

There are 1 best solutions below

0
On

Best option (and it should always be used) is to use scenarios. I don't know any other solution to this, only with scenarios. In case you haven't used it yet, here's how you implement:

public function scenarios()
{
    return [
        'scenario_global' => [<attributes list you want to validate>],
        'scenario_shortcode_only' => ['shortcode']
    ];
}


public function rules()
{
    return [
        [['shortcode'], 'string', 'length' => [8, 11], 'on' => 'scenario_shortcode_only'],
        [['shortcode'], 'required', 'on' => 'scenario_shortcode_only'],

        // If you need shortcode with different rule set, then use 'except' instead of 'on'
    ];
}

When you declare scenario scenario_shortcode_only, only those rules with 'on' => 'scenario_shortcode_only' will be validated while others will be ignored.