简体   繁体   English

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

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

The awesome Respect Validation library comes with lots of built-in validators, like string(), alpha(), et cetera. 令人敬畏的Respect Validation库带有许多内置验证器,如string(),alpha()等等。 I want to add self-defined validators to the library, eg., I want to be able to do this: 我想在库中添加自定义验证器,例如,我希望能够这样做:

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

I just discovered that's it not very complicated, but I had to look at the library's source code to find out, so I'm posting this self-answered question here for future reference. 我刚刚发现它并不是很复杂,但我不得不查看图书馆的源代码才能找到,所以我在这里发布这个自我回答的问题以备将来参考。

Define a validation class and an accompanying exception class in the proper namespace, and the Validation library will automagically use them to validate your data, as such: 在适当的命名空间中定义验证类和附带的异常类,验证库将自动使用它们来验证您的数据,如下所示:

myCustomValidator.php: 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: 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
        )
    );
}

As long as these files are included in your project, Validator::myCustomValidator()->assert( $input ); 只要这些文件包含在您的项目中, Validator::myCustomValidator()->assert( $input ); should now work. 现在应该工作。

This obviously relies on naming conventions, so be sure to use the class name to call the self-defined validator and you should be set. 这显然依赖于命名约定,因此请务必使用类名来调用自定义验证器,并且应该进行设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM