NotBlank

3.4 版本
维护中的版本

EN本篇文档待译。点击查看官方英文原档。我们将很快返回这里,敬请期待。

验证一个值不为空,被定义为非严格的false,即不能等于一个空字符串,也不能等于null。强制一个值不等于null,可以参考NotNull约束。

Applies to(适用于) property or method(属性或方法)
Options(选项)
Class(类) NotBlank
Validator(验证器) NotBlankValidator
1
2
3
4
5
6
7
8
9
10
11
12
// src/AppBundle/Entity/Author.php
namespace AppBundle\Entity;
 
use Symfony\Component\Validator\Constraints as Assert;
 
class Author
{
    /**
     * @Assert\NotBlank()
     */
    protected $firstName;
}
1
2
3
4
5
# src/AppBundle/Resources/config/validation.yml
AppBundle\Entity\Author:
    properties:
        firstName:
            - NotBlank: ~
1
2
3
4
5
6
7
8
9
10
11
12
<!-- src/AppBundle/Resources/config/validation.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping http://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">
 
    <class name="AppBundle\Entity\Author">
        <property name="firstName">
            <constraint name="NotBlank" />
        </property>
    </class>
</constraint-mapping>
1
2
3
4
5
6
7
8
9
10
11
12
13
// src/AppBundle/Entity/Author.php
namespace AppBundle\Entity;
 
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Constraints as Assert;
 
class Author
{
    public static function loadValidatorMetadata(ClassMetadata $metadata)
    {
        $metadata->addPropertyConstraint('firstName', new Assert\NotBlank());
    }
}

本文,包括例程代码在内,采用的是 Creative Commons BY-SA 3.0 创作共用授权。

登录symfonychina 发表评论或留下问题(我们会尽量回复)