How to add validation rules in reusable validator

Docs said making reusable validator like this. But how exactly are rules added ?
Do i make a new Validator object?

// In src/Model/Validation/ContactValidator.php
namespace App\Model\Validation;

use Cake\Validation\Validator;

class ContactValidator extends Validator
{
    public function __construct()
    {
        parent::__construct();
        // Add validation rules here.
    }
}
1 Like

i wonder too, because i can’t build.

Can you provide more detail? I’m not seeing anywhere in the 3.x or 4.x documentation instructions to write a class that extends Validator.

  • What version of Cake are you using?
  • Link the documentation section your are following
  • Provide more detail about what you’ve tried, and how it fails

@dreamingmind
https://book.cakephp.org/3/en/core-libraries/validation.html#creating-reusable-validators

I’ve got same problem, where to put some custom “rules” to be able to use them in many models.
I found some non working tutorials like:

and few unanswered topics here.
Now I will try combine this all above, but it should be better documented with examples.

You can override the default Validator using the _validationClass property in a Table class

I tried this in CakePHP 5.0.6 and 3.10.5. I assume it’s the same for 4

https://book.cakephp.org/3/en/orm/validation.html#default-validator-class

<?php
// In src/Validation/CustomValidator.php

namespace App\Validation;

use Cake\Validation\Validator;

class CustomValidator extends Validator
{
    public function __construct()
    {
        parent::__construct();
        // Add validation rules here.

        $this->mustHaveTheLetterA('password');
    }

    public function mustHaveTheLetterA(string $field)
    {

        return $this->add($field, 'letterA', [
            'rule' => function ($check, $context) {
                if (strpos(strtolower($check), 'a') === false) {
                    return "You must have the letter A in your password";
                }

                return true;
            }
        ]);
    }
}

And then in the table class override the default validation class so your custom rules are available where you need them

   use App\Validation\CustomValidator;

   public function initialize(array $config): void
    {
        parent::initialize($config);
        $this->_validatorClass = CustomValidator::class;
        // ... snippage
   }

Thanks! Does built-in validators still works after that?