【问题标题】:cakephp 3 add conditional validationcakephp 3 添加条件验证
【发布时间】:2016-06-03 08:02:55
【问题描述】:

在我的付款页面中,如果选择输入 payment_type == 'credit_card',我只想验证 credit_card 表单输入是否为 required 和 cc

我试过http://book.cakephp.org/3.0/en/core-libraries/validation.html#conditional-validation 在模型中,但在该操作中起作用但在应用程序的其他区域导致管理员编辑错误和错误通知:

$validator
  ->add('creditcard_number', [
     'cc' => [
        'rule' => 'cc',
          'message' => 'Please enter valid Credit Card',
          'on' => function ($context) {
             return $context['data']['payment_method'] == 'credit_card';
          }
     ],
]);

有没有办法在 cakephp 3 的控制器方法中添加验证规则?

【问题讨论】:

    标签: cakephp cakephp-3.0


    【解决方案1】:

    以这种方式结束,似乎工作正常:

    控制器/OrdersController.php:

    $order = $this->Orders->patchEntity($order, $this->request->data, ['validate' => 'review']);
    

    模型/表格/OrdersTable.php:

    public function validationReview(Validator $validator)
    {
        $validator = $this->validationDefault($validator);
    
        $validator->allowEmpty('creditcard_number', function ($context) {
            return $context['data']['payment_method'] === 'cod';
        });
    
        $validator->add('creditcard_number', 'cc', [
            'rule' => 'cc',
            'message' => 'Please enter valid Credit Card',
            'on' => function ($context) {
                return $context['data']['payment_method'] === 'credit_card';
            }
        ]);
    
        $validator->notEmpty('creditcard_number', 'Credit Card is required', function ($context) {
            return $context['data']['payment_method'] === 'credit_card';
        });
    
        return $validator;
    }
    

    【讨论】:

      猜你喜欢
      • 2015-11-26
      • 2017-01-24
      • 1970-01-01
      • 1970-01-01
      • 2016-08-24
      • 2016-05-10
      • 2015-07-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多