如何将自定义验证程序添加到尊重';s验证库


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

令人敬畏的尊重验证库附带了许多内置的验证器,如string()、alpha()等。我想将自定义验证器添加到库中,例如,我希望能够做到这一点:

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

我只是发现这不是很复杂,但我必须查看库的源代码才能找到答案,所以我在这里发布了这个自我回答的问题,以供将来参考。

在正确的命名空间中定义一个验证类和一个附带的异常类,验证库将自动使用它们来验证您的数据,例如:

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
        )
    );
}

只要这些文件包含在您的项目中,Validator::myCustomValidator()->assert( $input );现在就应该可以工作了。

这显然依赖于命名约定,所以一定要使用类名来调用自定义的验证器,并且应该进行设置。