Spring + Thymeleaf + Validation ignoring custom messages on validation annotations and going with their own

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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>@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;
}
</code>
<code>@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; } </code>
@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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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";
}
}
</code>
<code>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"; } } </code>
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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code><!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>
</code>
<code><!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> </code>
<!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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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.]
</code>
<code>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.] </code>
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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>public boolean shouldRenderDefaultMessage() {
return this.adapter != null && this.violation != null ? this.adapter.requiresMessageFormat(this.violation) : SpringValidatorAdapter.containsSpringStylePlaceholder(this.getDefaultMessage());
}
</code>
<code>public boolean shouldRenderDefaultMessage() { return this.adapter != null && this.violation != null ? this.adapter.requiresMessageFormat(this.violation) : SpringValidatorAdapter.containsSpringStylePlaceholder(this.getDefaultMessage()); } </code>
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.

5

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật