district5/validatorgroup

District5 验证器组库

2.0.0 2024-03-25 15:14 UTC

This package is auto-updated.

Last update: 2024-09-25 16:35:37 UTC


README

用于验证表单和 JSON 主体数据的验证器组。

用法

验证组

创建一个类,并扩展 \District5\ValidatorGroup\Group,添加要验证的字段。

/**
 * Creates a new instance of AuthValidationGroup
 */
public function __construct()
{
    $stringTrim = new StringTrim();

    $this->addField('username', [new StringLength(['min' => 4, 'max' => 254])], [$stringTrim], true);
    $this->addField('password', [new StringLength(['min' => 6, 'max' => 64])], [$stringTrim], true);
    $this->addField('device_id', [new StringLength(['min' => 6, 'max' => 64])], [], true);
}

验证

这可以在路由和处理器中使用,例如以下代码

$request = $app->request();

$vg = new \Project\Validate\Group\AuthAuthValidationGroup();

验证组可以用于使用正确处理器的任何自定义数据;库默认包含 JSON 处理器

$handler = new \District5\ValidatorGroup\Handler\JSON($request->getBody());
$valid = $vg->isValid($handler);

自定义处理器

您可以通过实现 \District5\ValidationGroup\Handler\HandlerInterface 并将其传递给 ValidationGroup 来创建自己的处理器。

错误

如果验证失败,验证组将通过调用来提供一些关于失败原因的提示

$vg->getLastErrorMessage();