简体   繁体   中英

How can I add a custom Validator to Respect's Validation library

The awesome Respect Validation library comes with lots of built-in validators, like string(), alpha(), et cetera. I want to add self-defined validators to the library, eg., I want to be able to do this:

Validator::myCustomValidator()->assert( $input );

I just discovered that's it not very complicated, but I had to look at the library's source code to find out, so I'm posting this self-answered question here for future reference.

Define a validation class and an accompanying exception class in the proper namespace, and the Validation library will automagically use them to validate your data, as such:

myCustomValidator.php:

<?php

namespace Respect\Validation\Rules;

class myCustomValidator extends AbstractRule
{
    public function validate($input)
    {
        return true; // Implement actual check here; eg: return is_string($input);
    }
}

myCustomValidatorException.php:

<?php

namespace Respect\Validation\Exceptions;

class myCustomValidatorException extends ValidationException
{
    public static $defaultTemplates = array(
        self::MODE_DEFAULT => array(
            self::STANDARD => '{{name}} must ... ', // eg: must be string
        ),
        self::MODE_NEGATIVE => array(
            self::STANDARD => '{{name}} must not ... ', // eg: must not be string
        )
    );
}

As long as these files are included in your project, Validator::myCustomValidator()->assert( $input ); should now work.

This obviously relies on naming conventions, so be sure to use the class name to call the self-defined validator and you should be set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM