Gregg
Gregg

Reputation: 35864

Spring Custom Validation i18n

Spring 1.3.5

I've created a handful of custom validators with the org.springframework.validation.Validator interface. I'm trying to use localized error messages. As a test validator, I've got the following:

@Component
public class RegionValidator implements Validator {

    @Autowired
    RegionService regionService;

    @Autowired
    private MessageSource messageSource;

    @Override
    public boolean supports(Class<?> clazz) {
        return Region.class.isAssignableFrom(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        String message = messageSource.getMessage("region.name.unique", null, null);
        errors.rejectValue("name", "region.name.unique", "Name must be unique");
    }
}

In my application.yml I have the following:

spring:
  messages:
      basename: i18n/messages
      cache-seconds: -1
      encoding: UTF-8

In the validator code, I am getting the correct message with messageSource but how can I get errors.rejectValue to look up the message based on the given code?

Upvotes: 0

Views: 759

Answers (1)

Gregg
Gregg

Reputation: 35864

I'm not sure this is 100% the way to go, but I failed to mention in my original question that I have an @ControllerAdvice class handling the error messages. I noticed that it was doing this...

fieldErrorResource.setMessage(fieldError.getDefaultMessage());

Which would always get the default message rather than the localized message. So I had to do the following:

if (fieldError.getCode() != null) {
    fieldErrorResource.setMessage(messageSource.getMessage(fieldError.getCode(), null, null));
} else {
    fieldErrorResource.setMessage(fieldError.getDefaultMessage());
}

Now I'm getting what I expect.

Upvotes: 1

Related Questions