我正在验证一些值:
$collectionConstraint = new Collection(array(
'email' => array(
new NotBlank(),
new Email(),
),
'password' => array(
new NotBlank(),
new MinLength(array('limit' => 6)),
new MaxLength(array('limit' => 25)),
),
));
$data = array('email' => $this->getRequest()->get('email'), 'password' => $this->getRequest()->get('password'));
$errors = $this->get('validator')->validateValue($data, $collectionConstraint);
Run Code Online (Sandbox Code Playgroud)
但由于某种原因,字段(propertyPath)存储方括号 - 我想了解为什么Sf这样做.我必须手动删除所有看似荒谬的括号,所以我想我在某处遗漏了一些功能.
转储$错误:
Symfony\Component\Validator\ConstraintViolationList Object
(
[violations:protected] => Array
(
[0] => Symfony\Component\Validator\ConstraintViolation Object
(
[messageTemplate:protected] => This value should not be blank
[messageParameters:protected] => Array
(
)
[root:protected] => Array
(
[email] =>
[password] =>
)
[propertyPath:protected] => [email]
[invalidValue:protected] =>
)
[1] => Symfony\Component\Validator\ConstraintViolation Object
(
[messageTemplate:protected] => This value should not be blank
[messageParameters:protected] => Array
(
)
[root:protected] => Array
(
[email] =>
[password] =>
)
[propertyPath:protected] => [password]
[invalidValue:protected] =>
)
)
)
Run Code Online (Sandbox Code Playgroud)
即使是toString函数也没用.
"[email]: This value should not be blank","[password]: This value should not be blank"
Run Code Online (Sandbox Code Playgroud)
属性路径可以映射到属性或索引.考虑一个OptionBag实现的类\ArrayAccess和一个方法getSize().
size是指$optionBag->getSize()[size]是指$optionBag['size']在您的情况下,您验证一个数组.由于数组元素也是通过索引访问的,因此违规中生成的属性路径包含方括号.
更新:
您不必手动删除方括号.您可以使用Symfony的PropertyAccess组件将错误映射到与数据结构相同的数组,例如:
$collectionConstraint = new Collection(array(
'email' => array(
new NotBlank(),
new Email(),
),
'password' => array(
new NotBlank(),
new MinLength(array('limit' => 6)),
new MaxLength(array('limit' => 25)),
),
));
$data = array(
'email' => $this->getRequest()->get('email'),
'password' => $this->getRequest()->get('password')
);
$violations = $this->get('validator')->validateValue($data, $collectionConstraint);
$errors = array();
$accessor = $this->get('property_accessor');
foreach ($violations as $violation) {
$accessor->setValue($errors, $violation->getPropertyPath(), $violation->getMessage());
}
=> array(
'email' => 'This value should not be blank.',
'password' => 'This value should have 6 characters or more.',
)
Run Code Online (Sandbox Code Playgroud)
这也适用于多维数据阵列.那里的物业路径就像[author][name].PropertyAccessor将错误消息插入到$errors数组中的相同位置,即$errors['author']['name'] = 'Message'.
| 归档时间: |
|
| 查看次数: |
3643 次 |
| 最近记录: |