令人敬畏的Respect Validation 库带有许多内置的验证器,如 string()、alpha() 等。我想将自定义验证器添加到库中,例如,我希望能够做到这一点:
Validator::myCustomValidator()->assert( $input );
我刚刚发现这并不是很复杂,但是我必须查看库的源代码才能找到答案,所以我在这里发布了这个自我回答的问题以供将来参考。
令人敬畏的Respect Validation 库带有许多内置的验证器,如 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 );
现在应该可以工作了。
这显然依赖于命名约定,所以一定要使用类名来调用自定义验证器,并且应该设置好。