Validation 在需要时设置长度Yi2规则

Validation 在需要时设置长度Yi2规则,validation,yii2,rules,Validation,Yii2,Rules,如果我将规则设置为“必需”,如何才能将规则组合为“长度”?提前谢谢 现在,我总是检查最小长度。最好的选择(应该一直使用)是使用。我不知道有什么其他的解决方案,只有场景。如果您还没有使用它,下面是您如何实现的: [['shortcode'],'string', 'length' => [8, 11]],// first ['shortcode','required', // second 'when' => function($model) {

如果我将规则设置为“必需”,如何才能将规则组合为“长度”?提前谢谢

现在,我总是检查最小长度。

最好的选择(应该一直使用)是使用。我不知道有什么其他的解决方案,只有场景。如果您还没有使用它,下面是您如何实现的:

 [['shortcode'],'string', 'length' => [8, 11]],// first
 ['shortcode','required', // second
                'when' => function($model) {
                  // code here
                },
 ],
公共功能场景()
{
返回[
“情景_全局”=>[],
'场景\u仅短码\u'=>['shortcode']
];
}
公共职能规则()
{
返回[
[['shortcode'],'string','length'=>[8,11],'on'=>'场景[仅限短码],
[['shortcode']、'required'、'on'=>'场景\u shortcode\u only'],
//如果您需要具有不同规则集的快捷码,请使用“Exception”而不是“on”
];
}
当您声明scenario
scenario\u shortcode\u only
时,只有那些带有
“on”=>“scenario\u shortcode\u only”
的规则将被验证,而其他规则将被忽略

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'
    ];
}