Skip to content

Custom Rule

In addition to the predefined rules, you can create custom validation rules by implementing the Rule Interface. Here's an example of how to create and use a custom rule:

CustomPasswordRule.php

<?php

// CustomPasswordRule.php
namespace YourNameSpace\Rules;

use BlakvGhost\PHPValidator\Contracts\Rule;

class CustomPasswordRule implements Rule
{
    protected $field;

    public function __construct(protected array $parameters = [])
    {
    }

    public function passes(string $field, $value, array $data): bool
    {
        $this->field = $field;
        // Implement your custom validation logic here
        // Example: Check if the password is equal to confirm_password
        return $value === $data['confirm_password'];
    }

    public function message(): string
    {
        return "Vos deux mot de passes ne sont pas identiques";
    }
}

Usage in Validator

  • Use your custom class directly

    <?php
    
    
    use BlakvGhost\PHPValidator\Validator;
    use BlakvGhost\PHPValidator\ValidatorException;
    
    use YourNameSpace\CustomPasswordRule;
    
    
    // ...
    
    try {
    
        $data = [
            'password' => '42',
            'confirm_password' => '142',
        ];
        // or
        // $data = $_POST;
    
        $validator = new Validator($data, [
            'password' => ['required', new CustomPasswordRule()],
        ]);
    
        if ($validator->isValid()) {
            echo "Validation passed!";
        } else {
            $errors = $validator->getErrors();
            print_r($errors);
        }
    } catch (ValidatorException $e) {
        echo "Validation error: " . $e->getMessage();
    }
    
  • Add your custom class to the rules list and use it as if it were native

    <?php
    
    
    use BlakvGhost\PHPValidator\Validator;
    use BlakvGhost\PHPValidator\ValidatorException;
    use BlakvGhost\PHPValidator\Mapping\RulesMaped;
    
    use YourNameSpace\CustomPasswordRule;
    
    // Add your rule here using an alias and the full namespace of your custom class
    RulesMaped::addRule('c_password', CustomPasswordRule::class);
    
    try {
    
        $data = [
            'password' => '42',
            'confirm_password' => '142',
        ];
    
        $validator = new Validator($data, [
            'password' => 'required|c_password',
        ]);
    
        if ($validator->isValid()) {
            echo "Validation passed!";
        } else {
            $errors = $validator->getErrors();
            print_r($errors);
        }
    } catch (ValidatorException $e) {
        echo "Validation error: " . $e->getMessage();
    }
    

In this example, we created a CustomPasswordRule that checks if the password is equal to confirm_password. You can customize the passes method to implement your specific validation logic.