【问题标题】:JPA validation messages internationalization with Thymeleaf使用 Thymeleaf 实现 JPA 验证消息国际化
【发布时间】:2019-06-05 19:45:08
【问题描述】:

我遇到了一些我无法解决的问题。我想用 Spring Thymeleaf 将 JPA 验证消息国际化。

我尝试了一些解决方案,但都没有奏效。

这是我的实体类属性:

@Length(min = 1, message = "#{field.empty}")
@Valid
private String lastName;

这是百里香形式:

<div class="form-group col">
    <label for="lastName" th:text="#{register.lastname}"></label>
    <input id="lastName" class="form-control" type="text"
        th:placeholder="#{register.lastname}"
        th:field="*{lastName}"
        th:classappend="${#fields.hasErrors('lastName')} ? is-invalid : ''"/>
    <small class="form-text text-danger"
        th:if="${#fields.hasErrors('lastName')}"
        th:errors="*{lastName}"></small>
</div>

我希望以与您在此处看到的相同方式打印翻译后的错误消息

<label for="lastName" th:text="#{register.lastname}"></label>

但我看不到翻译后的输出,而是看到#{field.empty}

有什么办法吗?

【问题讨论】:

  • 我以前遇到过这个,目前无法测试,但尝试从 Length 注释中删除井号或整个 #{}。
  • 哦,每个字段都不需要@Valid。
  • 我已经这样做了,但现在我可以看到 field.empty 错误。但我做了别的事情。对于注释 Length,我在 messages.properties 中设置了 Length 属性,我对 NotEmpty 做了同样的事情,我在属性中设置了 NotEmpty,它对我很有效。

标签: java spring jpa internationalization thymeleaf


【解决方案1】:

感谢goalkicker Spring book (Chapter 8: Spring JSR 303 Bean validation),我解决了我的问题。您可以在 messages.property 中为注释类型和特定类属性设置错误消息:

对于

@Length

使用

Length=error message here. 

对于这个特定的字段(姓氏)

Length.lastName=error message here

同样可以用于所有 JPA 注释

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-15
    • 1970-01-01
    • 1970-01-01
    • 2017-05-30
    • 1970-01-01
    • 2011-10-22
    • 2010-10-03
    • 1970-01-01
    相关资源
    最近更新 更多