It's the first time I build a symfony form on our legacy platform (an old monolith we're refactoring more and more with Symfony 5.1). On other Symfony-only platforms I've managed several times to build forms and validations without problems (3.x, 4.x, 5.x).
I stumbled upon a strange behaviour when trying to validate a values length or a valid email address. When I submit empty fields the isValid() method returns true without the NotBlank constraint. For server-side validation I've disabled the client validation.
I'm pretty sure that old code does not interfere; but the fact is, I'm using a php file to which I'm forwarded by a controller.
The $form->isValid() method returns true submitting this field without any data:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', TextType::class, [
'label' => $this->translator->trans('Your name'),
'constraints' => [
new Assert\Length([
'min' => 3
])
]
]);
[snip]
}
The $form->isValid() method returns false when submitting this field empty - which is the desired result:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', TextType::class, [
'label' => $this->translator->trans('Your name'),
'constraints' => [
new Assert\NotBlank([
'message' => $this->translator->trans('This value should not be blank'),
]),
new Assert\Length([
'min' => 3,
'minMessage' => $this->translator->trans('This value must be at least {{ limit }} characters long')
])
]
]);
[snip]
}
It seems wrong to me to add a NotBlank constraint - I already check for a minimum length here. Same for other text fields, also the Email constraint returns true when leaving the field empty. I've read the documentation again and again (see https://symfony.com/doc/current/validation.html#constraints-in-form-classes - so it should work), but I don't know what is going wrong here... The fix above was accidentally :). Is someone able to explain, why I need the NotBlank-constraint? Or do I miss something...?
$this->translator->trans
and just leave the translation key, it works – Alexander Br.