2016-12-17 58 views
1
[['shortcode'],'string', 'length' => [8, 11]],// first 
['shortcode','required', // second 
       'when' => function($model) { 
        // code here 
       }, 
], 

我如何结合我的规则length只,如果我将它设置为required?提前致谢。设置长度规则

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

回答

2

最好的选择(它应该始终使用)是使用scenarios。我不知道任何其他解决方案,只有场景。如果你还没有使用它,这里是你如何实现:

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

当你声明的情况scenario_shortcode_only,只有'on' => 'scenario_shortcode_only'这些规则将被而其他人将被忽略验证。