How do you create and use custom validators in Phalcon?

How do you create and use custom validators in Phalcon?

To create and use custom validators in Phalcon, follow these minimal steps:

1. Create the Custom Validator

Create a custom validator class that extends Phalcon\Validation\Validator and implement the validate method.

Example

<?php
use Phalcon\Validation\Validator;
use Phalcon\Validation\ValidatorInterface;
use Phalcon\Validation\ValidationMessage;

class MyCustomValidator extends Validator implements ValidatorInterface
{
    public function validate($validation, $field)
    {
        $value = $validation->getValue($field);

        // Custom validation logic
        if ($value !== 'valid') {
            $message = 'The value is not valid';
            $validation->appendMessage(new ValidationMessage($message, $field));
            return false;
        }

        return true;
    }
}
?>

2. Register the Validator

You need to register the custom validator in your validation rules:

Example

<?php
use Phalcon\Validation;

$validation = new Validation();
$validation->add('fieldName', new MyCustomValidator());

?>

3. Use the Validator in Your Application

Now, you can use the custom validator when validating data.

Example

<?php
$data = ['fieldName' => 'invalidValue'];

$messages = $validation->validate($data);

if (count($messages)) {
    foreach ($messages as $message) {
        echo $message->getMessage();
    }
} else {
    echo "Validation passed!";
}
?>

Related Questions & Topics