【问题标题】:Set length on when required Yii2 rules在需要时设置长度 Yii2 规则
【发布时间】:2017-05-03 10:07:37
【问题描述】:
 [['shortcode'],'string', 'length' => [8, 11]],// first
 ['shortcode','required', // second
                'when' => function($model) {
                  // code here
                },
 ],

如果我将其设置为 required,我如何才能将我的规则 length 组合起来?提前致谢。

目前,我总是以检查最小长度结束。

【问题讨论】:

    标签: validation yii2 rules


    【解决方案1】:

    最好的选择(并且应该始终使用)是使用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' =&gt; 'scenario_shortcode_only' 的规则将被验证,而其他规则将被忽略。

    【讨论】:

      猜你喜欢
      • 2017-03-13
      • 2017-11-07
      • 2015-08-03
      • 1970-01-01
      • 2017-05-27
      • 2012-05-01
      • 2011-09-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多