我无法解析我的验证消息。
我已经在网上搜索和阅读几个小时了,我想将问题与 Customize spring validation error 的标记答案联系起来
我确实有一个 MessageSource
bean 定义和 messages.properties 它被正确读取,因为我也用它来显示常规文本 th:text="#{some.prop.name}
,它确实工作得很好。只是验证错误不会按应有的方式工作。我确定这是我忽略的一个愚蠢的错误……验证本身工作正常。
约束:
@NotEmpty(message="{validation.mail.notEmpty}")
@Email()
private String mail;
消息.属性:
# Validation
validation.mail.notEmpty=The mail must not be empty!
模板部分:
<span th:if="${#fields.hasErrors('mail')}" th:errors="*{mail}"></span>
显示的文字:
{validation.mail.notEmpty}
我尝试了很多变体,但都没有成功。
@NotEmpty(message="validation.mail.notEmpty")
@NotEmpty(message="#{validation.mail.notEmpty}")
将只显示消息字符串的确切值,不进行解析。
<span th:if="${#fields.hasErrors('mail')}" th:errors="${mail}"></span>
<span th:if="${#fields.hasErrors('mail')}" th:errors="#{mail}"></span>
<span th:if="${#fields.hasErrors('mail')}" th:errors="#{*{mail}}"></span>
<span th:if="${#fields.hasErrors('mail')}" th:errors="#{__*{mail}__}"></span>
会导致错误。
编辑:
调试后,我偶然发现了这个:
班级: org.springframework.context.support.MessageSourceSupport
方法: formatMessage(String msg, Object[] args, Locale locale)
将被称为
formatMessage("{validation.mail.notEmpty}", null, locale /*German Locale*/)
它会遇到 if (messageFormat == INVALID_MESSAGE_FORMAT) {
所以…我的消息格式不正确。这超出了我的范围/知识范围。任何人都知道这是什么意思?
原文由 Korashen 发布,翻译遵循 CC BY-SA 4.0 许可协议
看起来您在应用程序配置中缺少
LocalValidatorFactoryBean
定义。 Below you can find an example ofApplication
class that defines two beans:LocalValidatorFactoryBean
andMessageSource
that usesmessages.properties
file.定义了
LocalValidatorFactoryBean
bean,您可以使用自定义验证消息,例如:和 messages.properties :
和 Thymeleaf 模板文件:
示例应用程序
我已经准备好反映您的问题的示例 Spring Boot 应用程序。随意克隆它并在本地运行它。如果随表单发布的值不符合
@NotEmpty
和@Email
验证,它将显示翻译后的验证消息。WebMvcConfigurerAdapter
配置在扩展
WebMvcConfigurerAdapter
的情况下,您必须通过覆盖父类的getValidator()
方法来提供验证程序,例如:否则,如果您在其他地方定义
LocalValidatorFactoryBean
bean,它将被覆盖并且不会有任何效果。我希望它有所帮助。