@deron
CakePHP provides various built-in validation rules to validate the data. However, sometimes we may need to create our custom validation rules as per the specific requirements of our application. In CakePHP, we can create custom validation helpers to validate the data.
Here are the steps to create custom validation helpers in CakePHP:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php // src/Validation/CustomValidation.php namespace AppValidation; use CakeValidationValidation; class CustomValidation { public static function myCustomValidation($value, $options) { if(/* validation passes */) { return true; } return 'Validation failed'; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
// src/Validation/AppValidation.php namespace AppValidation; use CakeValidationValidator; class AppValidator extends Validator { public function __construct() { parent::__construct(); // Register custom validation rule Validation::add('myCustomValidation', 'AppValidationCustomValidation::myCustomValidation'); } } |
Now you can use your custom validation helper myCustomValidation
in your validation rules just like any other built-in validation rule. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// In your table class public function validationDefault(Validator $validator) { $validator ->add('field_name', [ 'my_custom_validation' => [ 'rule' => 'myCustomValidation', 'message' => 'Custom validation failed' ] ]); return $validator; } |
That's it! You have successfully created a custom validation helper in CakePHP.