2
votes

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'

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

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

1

1 Answers

3
votes

ended up doing this way, seems to work fine:

Controller/OrdersController.php:

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

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