如何添加自定义验证器以尊重验证库

问题描述:

真棒Respect 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);

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