what I'm looking for is very easy to explain: I have a form which must support both italian and english. Let's suppose I have a First Name input text field. The form label will be:
what I want is a validation error message like these
please note I'm quoting the field name inside the error message.
I have the messages_en.properties
with the lines:
errors.empty.field = the {0} field is required
registration.form.firstname = First Name
and of course the messages_it.properties
with the lines:
errors.empty.field = il campo {0} è richiesto
registration.form.firstname = Nome
Now, inside my custom validator class I have
ValidationUtils.rejectIfEmpty(errors, "firstname", "errors.empty.field", new Object[]{"registration.form.firstname"}, "the First Name is required");
which doesn't works properly. The output is the "registration.form.username" string as it is. I'd like to inject the field name with the proper locale at runtime. Is there a way to do so?
This is one approach, there should be better one's out there though:
Inject the messageSource
into the Controller or the validator:
@Autowired MessageSource messageSource
In your controllers @RequestMapping
method, take in Locale as a parameter, Spring will populate it for you.
@RequestMapping(...)
public String myMethod(..., Locale locale){
ValidationUtils.rejectIfEmpty(errors, "firstname", "errors.empty.field", new Object[]{messageSource.getMessage("registration.form.firstname", new Object[]{}, locale)}, "the First Name is required");
....
}
Update:
You can get a handle on Locale
in Validator using LocaleContextHolder
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With