如何向Respect的验证库添加自定义验证器

时间:2014-10-08 17:30:31

标签: php validation respect-validation

令人敬畏的Respect Validation library带有许多内置验证器,如string(),alpha()等等。我想在库中添加自定义验证器,例如,我希望能够这样做:

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

我刚刚发现它不是很复杂,但我必须查看图书馆的源代码才能找到,所以我在这里发布这个自我回答的问题以供将来参考

1 个答案:

答案 0 :(得分:3)

在适当的命名空间中定义验证类和附带的异常类,验证库将自动使用它们来验证您的数据,如下所示:

<强> 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 );现在就可以使用。

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