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?

2
  • You can have more than one constraint per field - add a new line to the annotation - * @Assert\NotBlank() Commented Mar 2, 2018 at 21:45
  • @AlisterBulman Thanks. This helps. Janney Botis answered it a bit more complete below. Commented Mar 2, 2018 at 22:14

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. Got it :-) Small question aside: Is there a way to define a translation_domain for the message which I can define for an Assert?
Good question, unfortunately I do not know how.

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.