0

In an Entity class I defined a property like

use Symfony\Component\Validator\Constraints as Assert;

class MyEntity
{
    ...

    /**
     * @Assert\Date()
     */
    protected $date_of_birth;

    ...
}

In the FormType class I use the property:

$builder
    ->add('date_of_birth',
        DateType::class,
        array(
            'label' => 'Birthday',
            'required' => true,
            'translation_domain' => 'messages',
            'widget' => 'single_text',
            'html5' => false,
            'data' => null,
            'format' => $this->container->getParameter('date.format.icu'),
            'attr' => array( 'class' => 'js-bootstrap-datepicker', 'placeholder' => 'DD.MM.YYYY' ),
        )
    )
;

In the template I output the form suppressing browser side validation:

...
{{ form_start(form_a, {'attr': {'novalidate': 'novalidate'}}) }}
...
{{ form_label(form_a.date_of_birth) }}*
{{ form_errors(form_a.date_of_birth) }}
{{ form_widget(form_a.date_of_birth) }}
...

Unfortunately it doesn't really matter what I type into the date field. I can leave it empty - it still is OK for the validator. The NotBlank Constraint works though. I suppose I am missing something specific in the Date Constraint usage?

user3440145
  • 793
  • 10
  • 34

1 Answers1

1

This is the expected behaviour. You are not missing anything, there is no option in the definition of the Date constraint to invalidate for empty value in the field.

To invalidate for empty value in the field, you should add the NotBlank Constraint, as you correctly state.

Here is the line: code for DateValidator

For example this is the same for most other validators, eg. LengthValidator will validate for empty string, even if min is >0.

References:

  1. Similar answer
  2. Github issue
  3. Explanation
Jannes Botis
  • 11,154
  • 3
  • 21
  • 39