phpvalidationrespect-validation

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.


Solution

  • 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.