Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring 3 validation: using messages.property entry inside errorArgs?

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:

  • for EN: "First Name"
  • for IT: "Nome"

what I want is a validation error message like these

  • for EN: "the First Name field is required"
  • for IT: "il campo Nome è richiesto"

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?

like image 783
MaVVamaldo Avatar asked Nov 04 '22 12:11

MaVVamaldo


1 Answers

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

like image 178
Biju Kunjummen Avatar answered Nov 12 '22 19:11

Biju Kunjummen