cakephp 3添加条件验证 [英] cakephp 3 add conditional validation

查看:47
本文介绍了cakephp 3添加条件验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的付款页面中,如果选择的输入payment_type =='credit_card'

In my payment page I only want to validate the credit_card form input for required and cc if the select input payment_type == 'credit_card'

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

I tried http://book.cakephp.org/3.0/en/core-libraries/validation.html#conditional-validation in the model but while it worked in that action but causing errors on admin edit and error notices at other areas of the app:

$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中向控制器方法添加验证规则?

Is there a way to add a validation rule to a controller method in cakephp 3?

推荐答案

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

ended up doing this way, seems to work fine:

Controller / OrdersController .php:

Controller/OrdersController.php:

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

Model / Table / OrdersTable.php:

Model/Table/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;
}

这篇关于cakephp 3添加条件验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆