Forms 表单始终通过验证,即使值为空/无效
我有一个简单的表单,其中不使用实体类 在post之后,我想使用验证器验证值,但是错误列表的计数始终为零,即使值为空或无效 以下是(或多或少)我正在执行的代码:Forms 表单始终通过验证,即使值为空/无效,forms,symfony,validation,Forms,Symfony,Validation,我有一个简单的表单,其中不使用实体类 在post之后,我想使用验证器验证值,但是错误列表的计数始终为零,即使值为空或无效 以下是(或多或少)我正在执行的代码: use Symfony\Component\Validator\Constraints\Email; use Symfony\Component\Validator\Constraints\MinLength; use Symfony\Component\Validator\Constraints\Collecti
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\MinLength;
use Symfony\Component\Validator\Constraints\Collection;
public function formAction(){
$collectionConstraint = new Collection(array(
'name' => array(new MinLength(5)),
'email' => array(new Email(array('message' => 'Invalid email address'))),
));
$options = array('validation_constraint' => $collectionConstraint);
$form = $this->createFormBuilder(null, $options)
->add('name', 'text', array('label' => '', 'attr' => array('placeholder' => 'Your name')))
->add('email', 'email', array('label' => '', 'attr' => array('placeholder' => 'E-mail')))
->getForm();
$request = $this->getRequest();
$error = false;
if ($request->getMethod() == 'POST') {
$form->bindRequest($request);
if ($form->isValid()) {
$data = $form->getData();
$errorList = $this->get('validator')->validateValue($data, $collectionConstraint);
// count($errorList) is always zero even when the values are empty or invalid…
}
else {
$error = true;
}
}
// ... snip ...
}
我想说这是正常的,因为您在告诉表单有效的测试中计算
$errorList
中的元素数。所以我想说,当表单有效时,它显示0,当它无效时,它什么也不显示
您不需要手动运行验证,因为它已经由$form->isValid()
语句执行
如果要计算已发生的约束冲突的数量,只需在调用$form->isValid()
后运行count($form->getErrors())
最后,如果还没有完成,你应该明确阅读
干杯是的,我已经知道了,没有错误。我的问题是,为什么它没有按预期工作。如果有无效的电子邮件或字段设置为空,则在提交表单时会出现错误…在提交此问题之前,我阅读了您链接到的帖子。