Custom validation messages are not localized but i18n property key is rendered instead
My app performs manual validations of a given form after submit in the controller:
@PostMapping("/register")
public ModelAndView processRegisterForm(@Valid @ModelAttribute("register") final RegistrationForm form, final BindingResult result, final RedirectAttributes redirectAttributes) {
result.addError(new FieldError("register", "captcha", "wrongcaptcha"));
return new ModelAndView("selfservice.html");
}
However when rendering the errors within the target template
<span
class="text-danger" th:errors="*{captcha}"
th:if="${#fields.hasErrors('captcha')}"></span>
the app shows the message key "wrongcaptcha" instead of the defined i18n.properties element. Other parts of the page are properly localized so it's not a problem of the i18n mechanismus within SpringBoot 3.4.1.
After reading about SpringBoot's message localization I tried multiple combinations of property keys for i18n with no success, e.g.
- register.captcha
- register.captcha.wrongcaptcha
- wrongcaptcha
- captcha.wrongcaptcha
Is there different way to transport validation error i18n keys? I even tried curly braces "{wrongcaptcha}"?
Is this a bug or am I using Thymeleaf in the wrong way?
Thanks for any hint
I've provided an example project that shows the problematic behaviour: https://github.com/ottlinger/custom-validation-messages-1029
I18n is working fine and the language can be changed via the URL param ?lang. Further actions are described in the app's README.
Default hibernate validation errors are properly translated, but customized messages are not.
Hope this is useful to debug the problem :)
Same behaviour with more modern Spring Boot versions, such as 4.0.0-RC2 - the i18n key is shown instead of the translated message during form validation.