【问题标题】:How can I add a custom Validator to Respect's Validation library如何将自定义验证器添加到 Respect 的验证库
【发布时间】:2014-12-03 11:13:23
【问题描述】:

很棒的Respect Validation library 带有许多内置验证器,例如 string()、alpha() 等。我想将自定义验证器添加到库中,例如,我希望能够做到这一点:

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

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

【问题讨论】:

    标签: php validation respect-validation


    【解决方案1】:

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

    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()-&gt;assert( $input ); 现在应该可以工作了。

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

    【讨论】:

      猜你喜欢
      • 2020-01-07
      • 1970-01-01
      • 2017-07-26
      • 1970-01-01
      • 1970-01-01
      • 2021-12-23
      • 1970-01-01
      • 1970-01-01
      • 2012-09-29
      相关资源
      最近更新 更多