I have a typical Spring Boot (3.3.2) MVC application using validation and thymeleaf (3.1.2.RELEASE), and I'm finding that Thymeleaf seems to disregard the i18n messages specified in the validation annotation, attempting some other instead. In other words, if an annotation specifies "{A}" as a message, thymeleaf instead tries to use a different message key which seems to be the name of the annotation+the path of the property (e.g., for @Size attached to a "name" property in a "test" bean, it tries to use "Size.test.name" instead).
Distilling the problem, the pieces look as follows
Bean:
@Validated
public class TestDTO {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@NotNull(message = "{ui.errors.required}")
@Size(min = 7, max = 100, message = "{ui.errors.nameLength}")
private String name;
}
Controller:
package org.agoraspeakers.server.controllers.test;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
@Controller
public class TestController {
@GetMapping("/test-start")
public String startClubRegistration(final HttpServletRequest request, Model model) {
TestDTO test = new TestDTO();
model.addAttribute("test", test);
return "test-form";
}
@PostMapping("/test-post")
public String registerClub(@Valid @ModelAttribute("test") TestDTO test, BindingResult bindingResult, final HttpServletRequest request, Model model) {
System.out.println(bindingResult);
return "test-form";
}
}
Form
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body >
<form th:action="@{/test-post}" th:object="${test}" method="POST" enctype="multipart/form-data">
<ul>
<li th:each="e : ${#fields.detailedErrors()}" th:class="${e.global}? globalerr : fielderr">
<span th:text="${e.global}? '*' : ${e.fieldName}">The field name</span> |
<span th:text="${e.message}">The error message</span>
</li>
</ul>
<input type="text" th:field="*{name}" size="60">
<button type="submit">Submit</button>
</body>
</html>
Now, for some reason thymeleaf insists in rendering some weird "Size.test.name" message key instead of the message that gets properly expanded by the validation framework.
Specifically, the printed bindingResults show:
Field error in object 'test' on field 'name': rejected value []; codes [Size.test.name,Size.name,Size.java.lang.String,Size]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [test.name,name]; arguments []; default message [name],50,2]; default message [The name must be between 7 and 100 characters.]
where the custom message "ui.errors.nameLength" from the @Size annotation has been correctly expanded to "The name must be between 7 and 100 characters."
Why is thymeleaf trying to use a different message, and how can I force it to use the messages that are already specified?
After a lot of debugging, I have a hunch that it might be related to the shouldRenderDefaultMessage
() method in SpringValidatorAdapter
that is returning false, but not quite what to do about it, and I might be totally off the track on this one
public boolean shouldRenderDefaultMessage() {
return this.adapter != null && this.violation != null ? this.adapter.requiresMessageFormat(this.violation) : SpringValidatorAdapter.containsSpringStylePlaceholder(this.getDefaultMessage());
}
I searched around here for similar issues but I didn't manage to find one.
Anyway, my expectation is that thymeleaf should use the messages explicitly specified in the validation. After all, the whole point of explicitly indicating message in a validation annotation is to override any defaults.
So, I figured it out.
Indeed spring databinding completely ignores the message parameter of the validation annotation, with the behavior codified in the processConstraintViolations
method of the default SpringValidatorAdapter
.
Unfortunately the class that decides what key codes to return when an error occurs is based on the MessageCodesResolver
interface, and the methods defined there require you to provide the error codes(message keys) without having any access to the original annotation validation failure.
The solution I came up with is to create a custom ValidationAdapter and override the method that processes the constraint violations. Not ideal, but it works. This altered version respects whatever you've written in the annotation's message - both if it's a literal message or a key reference.
CustomValidationAdapter
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validator;
import jakarta.validation.metadata.ConstraintDescriptor;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.NotReadablePropertyException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.validation.beanvalidation.SpringValidatorAdapter;
import java.util.Iterator;
import java.util.Set;
public class CustomValidationAdapter extends SpringValidatorAdapter {
public CustomValidationAdapter(Validator validator) {
super(validator);
}
protected void processConstraintViolations(Set<ConstraintViolation<Object>> violations, Errors errors) {
Iterator violationIterator = violations.iterator();
while(true) {
ConstraintViolation violation;
String field;
FieldError fieldError;
do {
if (!violationIterator.hasNext()) {
return;
}
violation = (ConstraintViolation)violationIterator.next();
field = this.determineField(violation);
fieldError = errors.getFieldError(field);
} while(fieldError != null && fieldError.isBindingFailure());
try {
ConstraintDescriptor<?> cd = violation.getConstraintDescriptor();
String errorCode = this.determineErrorCode(cd);
Object[] errorArgs = this.getArgumentsForConstraint(errors.getObjectName(), field, cd);
if (errors instanceof BindingResult bindingResult) {
String nestedField = bindingResult.getNestedPath() + field;
String template = violation.getMessageTemplate();
String message = violation.getMessage();
String[] codes = null;
if (template != null && (template.startsWith("{") && template.endsWith("}"))) {
template = template.substring(1, template.length() - 1);
String[] errorCodes = nestedField.isEmpty()?bindingResult.resolveMessageCodes(errorCode): bindingResult.resolveMessageCodes(errorCode, field);
codes = ArrayUtils.addAll(new String[] { template },errorCodes);
}
if (nestedField.isEmpty()) {
ObjectError error = new ObjectError(errors.getObjectName(), codes, errorArgs, message);
bindingResult.addError(error);
} else {
Object rejectedValue = this.getRejectedValue(field, violation, bindingResult);
FieldError error = new FieldError(errors.getObjectName(), nestedField, rejectedValue, false, codes, errorArgs, message);
bindingResult.addError(error);
}
} else {
errors.rejectValue(field, errorCode, errorArgs, violation.getMessage());
}
} catch (NotReadablePropertyException var15) {
NotReadablePropertyException ex = var15;
throw new IllegalStateException("JSR-303 validated property '" + field + "' does not have a corresponding accessor for Spring data binding - check your DataBinder's configuration (bean property versus direct field access)", ex);
}
}
}
}
Configuration
import jakarta.validation.Validation;
import jakarta.validation.ValidatorFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.Validator;
@Configuration
public class ValidatorConfig {
@Bean
public Validator customValidator() {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
return new CustomValidationAdapter(factory.getValidator());
}
@Bean
public org.springframework.validation.Validator getValidator() {
return customValidator();
}
}