跳到内容

验证器组件

编辑此页

验证器组件提供了按照 JSR-303 Bean Validation 规范验证值的工具。

安装

1
$ composer require symfony/validator

注意

如果您在 Symfony 应用程序之外安装此组件,您必须在代码中引入 vendor/autoload.php 文件,以启用 Composer 提供的类自动加载机制。阅读这篇文章以了解更多详情。

使用

另请参阅

本文介绍了如何在任何 PHP 应用程序中将验证器功能用作独立组件。阅读验证文章,了解如何在 Symfony 应用程序中验证数据和实体。

验证器组件的行为基于两个概念:

  • 约束,它定义了要验证的规则;
  • 验证器,它是包含实际验证逻辑的类。

以下示例展示了如何验证字符串是否至少为 10 个字符长:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Validation;

$validator = Validation::createValidator();
$violations = $validator->validate('Bernhard', [
    new Length(['min' => 10]),
    new NotBlank(),
]);

if (0 !== count($violations)) {
    // there are errors, now you can show them
    foreach ($violations as $violation) {
        echo $violation->getMessage().'<br>';
    }
}

validate() 方法将违规列表作为实现了 ConstraintViolationListInterface 的对象返回。如果您有很多验证错误,您可以按错误代码过滤它们:

1
2
3
4
5
6
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

$violations = $validator->validate(/* ... */);
if (0 !== count($violations->findByCodes(UniqueEntity::NOT_UNIQUE_ERROR))) {
    // handle this specific error (display some message, send an email, etc.)
}

获取验证器实例

验证器对象(它实现了 ValidatorInterface)是验证器组件的主要访问点。要创建它的新实例,建议使用 Validation 类:

1
2
3
use Symfony\Component\Validator\Validation;

$validator = Validation::createValidator();

这个 $validator 对象可以验证简单的变量,如字符串、数字和数组,但它不能验证对象。要做到这一点,请按照以下部分中的说明配置 Validator

本作品,包括代码示例,根据 Creative Commons BY-SA 3.0 许可获得许可。
目录
    版本