public static function loadValidatorMetadata(ClassMetadata $metadata)
{
$metadata->addPropertyConstraint('gender', new Choice(array('male', 'female')));
}
}
约束目标
约束可以被用于一个类的属性或者一个公共的getter方法。属性约束最常用也最简单,而公共的getter方法约束则允许你指定一个复杂的约束规则。
属性约束:
校验类的属性石一个最常规的校验技术。Symfony2允许你校验private,protected或者public属性。下面代码显示如何配置Author对象的$firstName属性至少有3个字符:
YAML格式:
复制代码 代码如下:
# src/Acme/BlogBundle/Resources/config/validation.yml
Acme\BlogBundle\Entity\Author:
properties:
firstName:
- NotBlank: ~
- MinLength: 3
类声明格式:
复制代码 代码如下:
// Acme/BlogBundle/Entity/Author.php
use Symfony\Component\Validator\Constraints as Assert;
class Author
{
/**
* @Assert\NotBlank()
* @Assert\MinLength(3)
*/
private $firstName;
}
XML格式:
复制代码 代码如下:
<!-- src/Acme/BlogBundle/Resources/config/validation.xml -->
<class>
<property>
<constraint />
<constraint>3</constraint>
</property>
</class>
PHP代码格式:
复制代码 代码如下:
// src/Acme/BlogBundle/Entity/Author.php
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\MinLength;
class Author
{
private $firstName;
public static function loadValidatorMetadata(ClassMetadata $metadata)
{
$metadata->addPropertyConstraint('firstName', new NotBlank());
$metadata->addPropertyConstraint('firstName', new MinLength(3));
}
}
Getters
约束也可以应用于一个方法的返回值。Symfony2 允许你添加一个约束到任何"get"或者 "is"开头的public方法。该技术的好处是允许你动态的校验你的对象。比如,假设你想确认密码字段不匹配用户的first name(因为安全原因)。你可以通过创建一个idPasswordLegal 方法,然后决断这个方法必须返回true:
YAML格式:
复制代码 代码如下:
# src/Acme/BlogBundle/Resources/config/validation.yml
Acme\BlogBundle\Entity\Author:
getters:
passwordLegal:
- "True": { message: "The password cannot match your first name" }
类声明格式:
复制代码 代码如下:
// src/Acme/BlogBundle/Entity/Author.php
use Symfony\Component\Validator\Constraints as Assert;
class Author
{
/**
* @Assert\True(message = "The password cannot match your first name")
*/
public function isPasswordLegal()
{
// return true or false
}
}
XML格式:
复制代码 代码如下:
<!-- src/Acme/BlogBundle/Resources/config/validation.xml -->
<class>
<getter property="passwordLegal">
<constraint>
<option>The password cannot match your first name</option>
</constraint>
</getter>
</class>
PHP代码格式:
复制代码 代码如下:
// src/Acme/BlogBundle/Entity/Author.php
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Constraints\True;