Skip to content

Latest commit

 

History

History
executable file
·
80 lines (52 loc) · 2.68 KB

5.1 - Using rule class objects.md

File metadata and controls

executable file
·
80 lines (52 loc) · 2.68 KB

5.1 - Custom validation rules

Using rule class objects

Although there is a large number of predefined validation rules, you may wish to specify some of your own. One method of registering custom validation rules is using rule class objects.

Below is a blueprint/example of a custom rule class object:

use KrisKuiper\Validator\Blueprint\Contracts\RuleInterface;
use KrisKuiper\Validator\Blueprint\Events\Event;

class CustomRule implements RuleInterface
{
    public const RULE_NAME = 'length';
    
    public function getName(): string
    {
        return self::RULE_NAME;
    }

    public function isValid(Event $event): bool
    {
        //Retrieve the minimum parameter
        $min = $event->getParameter('min');
        
        //Create your own validation
        return strlen($event->getValue()) > $min;
        
        //Or use the built-in validator
        return $event->field('name')->lengthMin($min)->isValid();
    }

    public function getMessage(): string
    {
        return 'Invalid input';
    }
}

Once the rule has been defined, you may attach it to the validator by calling the loadRule() method, passing an instance of the rule object. Then you can call the custom() method which takes the name of the custom rule (which is defined in the getName() method of the custom rule object) as first parameter. An optional second parameter is for all the parameters which you can use in your custom rule:

use KrisKuiper\Validator\Validator;

$data = ['name' => 'Morris'];
$validator = new Validator($data);

//Attach the custom rule
$validator->loadRule(new CustomRule());

//Use the custom rule
$validator->field('name')->custom(CustomRule::RULE_NAME, ['min' => 5]); 

//Set an optional custom error message
$validator
    ->messages('name')
    ->custom('length', 'Invalid value, at least :min characters'); 

if($validator->passes()) {
 	//Validation passes   
}

Note 1: The name length equals the output of the getName() method from the rule object.

Note 2: The error message will be used from the getMessage() method from the rule object, unless you set an optional custom error message like in the example above.

Note 3: You can also set custom error messages with the message() method.


Go to the previous section.

Go to the next section.