简体   繁体   中英

How to create custom form date validation error messages in Symfony 4

Using Symfony 4, I have a form with a date field. Safari (MacOS) and IE 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.

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 (ie fails validation).

which would be something like

$builder
        ->add('date', DateType::class, [
                'widget' => 'single_text',
                'invalid_message' => 'Please format your date yyyy-mm-dd'
        ])
    ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM