Overriding Form Validation messages on symfony2

前端 未结 2 856
被撕碎了的回忆
被撕碎了的回忆 2021-01-04 18:21

How to override the form validation messages in symfony2. Though there is a validation.xml file related model classes. I think it validates a form based on html5.

相关标签:
2条回答
  • 2021-01-04 19:04

    Those messages you see are HTML5 validation messages which are created by the browser. If you want to override them you need to add an oninvalid attribute to the input tag associated with that field. You can do this in two ways:

    In your controller or form type, add this attribute to the form field:

    $builder->add('email', 'email',array(
        'attr'=>array('oninvalid'=>"setCustomValidity('Would you please enter a valid email?')")
    ));
    

    Or, in your twig template, add this attribute when rendering the form field:

    {{ form_row(form.email, { 'attr': {'oninvalid': "setCustomValidity('Please give me a nice email')"} }) }}
    
    0 讨论(0)
  • 2021-01-04 19:05

    You can change the message of each validator thanks to the message option when declaring the assert:

    /**
         * @ORM\Column(type="string", length=255, unique=true)
         * @Assert\NotBlank(
         *     message="You have to choose a username (this is my custom validation message).",
         *     groups={"registration", "account", "oauth"}
         * )
    

    Also you can apply translation by creating the file MyBundle/Resources/translations/validators.fr.xliff

    0 讨论(0)
提交回复
热议问题