How to customize/localize Assert messages in Symfony2?

Cutomizing validation error messages is quite simple, but can seem tricky at first.

Default locale

First of all you should change the default locale of your application. In versions 2.0.x the correct value to change is framework.session.default_locale. For future reference, starting from 2.1.0 it'll be framework.default_locale. Consult the docs for correct syntax.

A locale should consist of your language and region and is defined as language_REGION (list of languages, list of countries). The locale used in Germany for german would be de_DE for example.

Validation messages

Validation messages are hard coded in their respective constraint classes.

Translating validation messages

Symfony uses Twig to render all the validation messages. The process itself is complicated and falls out of the scope of this question, but the important part is that each constraint message is sent through a translation filter, which depending on the user's locale (default_locale by default) translates the messages to the proper language.

To change any of the translations, simply copy the validation translation file from vendor/symfony/src/Symfony/Bundle/FrameworkBundle/Resources/translations/validators.{lang}.xlf to app/Resources/translations/validators.{lang}.xlf where {lang} is the language part of your default locale.

Having done the former, simply change the default messages to what ever you see more fit. If the language you need support for doesn't exist, copy any translation file to the same directory and modify that file instead.

To read more about how translation works in Symfony2, visit the official documentation on translation.


Additionally to the instructions by gilden, you have to make sure the framework.translator block in config/config.yml is uncommented (it's commented by default nowadays). If you don't do that, you'll still end up with the original English messages.

Tags:

Symfony