验证复选框未映射到symfony2表单中的实体

时间:2022-10-16 18:20:30

I add a non mapped field to a symfony2 form type:

我将一个非映射字段添加到symfony2表单类型:

$builder->add('terms','checkbox', array('mapped' => false,
        'constraints' => array(new NotBlank())));

But the NotBlank() constraint is not working! Only if I change the type from 'checkbox' to 'text' it is working as expected. So how can I validate a checkbox? Of course I tried with 'True()', 'EqualTo()' and 'Length(...)' constraints too. But without success. I also tried different POST values (1/0, true/false, on/off...) for the field.

但NotBlank()约束不起作用!只有当我将类型从“复选框”更改为“文本”时,它才能按预期工作。那么如何验证复选框?当然我也试过'True()','EqualTo()'和'Length(...)'约束。但没有成功。我还尝试了不同的POST值(1/0,真/假,开/关......)。

What is the big difference between a checkbox field and a text field regarding form field validation in symfony2?

关于symfony2中表单字段验证的复选框字段和文本字段之间的最大区别是什么?

Thanx Stef

Thanx Stef

2 个解决方案

#1


13  

NotBlank validates string to be not empty. Try to use NotNull

NotBlank验证字符串不为空。尝试使用NotNull

True must also works.

真的也必须奏效。

Validates that a value is true. Specifically, this checks to see if the value is exactly true, exactly the integer 1, or exactly the string "1". This constraint can be applied to properties (e.g. a termsAccepted property on a registration model).

验证值是否为true。具体来说,这将检查值是否完全正确,正好是整数1,还是字符串“1”。该约束可以应用于属性(例如,注册模型上的termsAccepted属性)。

#2


8  

Updated answer for Symfony 3.0:

更新了Symfony 3.0的答案:

use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Validator\Constraints\IsTrue;

// ...
{
    $builder->add('terms', CheckboxType::class, array('constraints'=>new IsTrue(array('message'=>'Needs to be clicked')));
}

#1


13  

NotBlank validates string to be not empty. Try to use NotNull

NotBlank验证字符串不为空。尝试使用NotNull

True must also works.

真的也必须奏效。

Validates that a value is true. Specifically, this checks to see if the value is exactly true, exactly the integer 1, or exactly the string "1". This constraint can be applied to properties (e.g. a termsAccepted property on a registration model).

验证值是否为true。具体来说,这将检查值是否完全正确,正好是整数1,还是字符串“1”。该约束可以应用于属性(例如,注册模型上的termsAccepted属性)。

#2


8  

Updated answer for Symfony 3.0:

更新了Symfony 3.0的答案:

use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Validator\Constraints\IsTrue;

// ...
{
    $builder->add('terms', CheckboxType::class, array('constraints'=>new IsTrue(array('message'=>'Needs to be clicked')));
}