13

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

$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.

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

Thanx Stef

1
  • To get eyes on your question, you should tag it with the most popular tag that is relevant to your question - in this case, I would recommending replacing one of your tags, like the 'constraints' tag with 'PHP'. Commented Aug 11, 2013 at 23:49

2 Answers 2

16

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

IsTrue 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).

Sign up to request clarification or add additional context in comments.

1 Comment

True works for me to validate checkbox, thank you.
10

Updated answer for 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')));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.