gpt4 book ai didi

php - 如何将自定义验证器添加到 Respect 的验证库

转载 作者:搜寻专家 更新时间:2023-10-31 20:39:32 25 4
gpt4 key购买 nike

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

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

我刚刚发现它不是很复杂,但我必须查看库的源代码才能找到答案,所以我将这个 self 回答的问题张贴在这里以供将来引用。

最佳答案

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

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 ); 现在应该可以工作。

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

关于php - 如何将自定义验证器添加到 Respect 的验证库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26262901/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com