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.
}
}
<?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
}
Because the custom validator extends the built-in one then yes all the methods are still there to use.
If you skip adding / applying rules in the constructor __construct() of the Custom Validator then you can just use your custom rules and the default ones wherever they are needed.