10

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.

"Please match the requested format", "Please fill out this field". Is there any way to override this validation messages.

Please help me in this regard, i am stuck for more than a day, as i am totally new to symfony

satdev86
  • 800
  • 7
  • 14

2 Answers2

14

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')"} }) }}
Carlos Granados
  • 11,273
  • 1
  • 38
  • 44
  • Thanks, this is what i am looking for. Timely one :) – satdev86 Sep 04 '12 at 07:35
  • 1
    But if you do it this way, you enter a invalid email address, then the error comes up, your correct the emailaddress but the error is still coming up. Why? – craphunter Feb 02 '13 at 12:44
  • 4
    Carlos' answer is almost correct, but has some issues. See "http://stackoverflow.com/questions/10361460/how-can-i-change-html-5-form-validation-errors-default-messages" for workaround. – IsraelWebDev May 09 '13 at 15:29
  • I get the error message "The option "oninvalid" does not exist. " – peace_love Aug 06 '18 at 12:10
3

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

Sybio
  • 8,565
  • 3
  • 44
  • 53