1

Using Symfony 4, I have a form with a date field. Safari (MacOS) and I.E. do not support HTML5 date pickers. When a user submits a date (without using a date picker), I want the error message to read "Please format your date yyyy-mm-dd" instead of the default "This value is not valid."

Here is my form class:

class MyType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('date', DateType::class, [
                    'widget' => 'single_text',
            ])
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
                'data_class' => MyEntity::class,
        ]);
    }
}

Here is my entity class:

class MyEntity
{
   /**
     * @Assert\NotBlank()
     * @Assert\Date()
     */
    private $date;

    public function getDate()
    {
        return $this->date;
    }

    public function setDate($date)
    {
        $this->date = $date;
    }
}

I tried:

/**
 * @Assert\NotBlank()
 * @Assert\Date(
 *      message="Please format your date yyyy-mm-dd."
 * )
 */
private $date;

I can customize the error messages for TextType form fields, but cannot find any examples for DateType. Any help would be appreciated. Thanks.

0

1 Answer 1

3

I think what you have to do is just set invalid_message parameter on your field as stated in the documentation

invalid_message

type: string default: This value is not valid

This is the validation error message that's used if the data entered into this field doesn't make sense (i.e. fails validation).

which would be something like

$builder
        ->add('date', DateType::class, [
                'widget' => 'single_text',
                'invalid_message' => 'Please format your date yyyy-mm-dd'
        ])
    ;
Sign up to request clarification or add additional context in comments.

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.