Thymeleaf:如何在JSR-303批注中使用自定义消息密钥 [英] Thymeleaf : How to use Custom Message Key in JSR-303 Annotation

查看:319
本文介绍了Thymeleaf:如何在JSR-303批注中使用自定义消息密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Thymeleaf

Use Thymeleaf

Person.java

Person.java

public class Person {
    @NotEmpty(message="{Valid.Password}")
    private String password;
}

message.properties

message.properties

Valid.Password = Password is Empty!!

Login.html

Login.html

<span class="error" th:errors="person.password"></span>

th:错误无法检索'有效.Password'消息
该区域显示为空。

th:errors can not retrieve 'Valid.Password' Message That area is shown as empty.

如果消息密钥更改为message.properties的NotEmpty.person.password,则表明它正在运行。

if message key change to NotEmpty.person.password of message.properties, then it is working.

如何使用自定义消息密钥?

how to use custom message key?

推荐答案

使用javax。对类进行验证约束并添加自定义消息要求您基本上覆盖默认消息。
例如:

using javax.validation constrains on class and adding custom messages requires you to basically override default messages. for example:

public class Vehicle implements Serializable {

    private static final long serialVersionUID = 1L;

    @Size(min=17, max=17, message="VIN number must have 17 characters")
    private String vin;


    @NotEmpty
    @Pattern(regexp="[a-z]*", flags = Pattern.Flag.CASE_INSENSITIVE)
    private String make;

    @NotEmpty
    @Pattern(regexp="[a-z]*", flags = Pattern.Flag.CASE_INSENSITIVE)
    private String model;

要覆盖默认值,您可以在验证中插入自定义消息,例如VIN,或者将它们添加到messages.properties文件:

To override default values, you insert custom message in the validation itself like for VIN, or add them to the messages.properties file:

# Validation messages
notEmpty.message = The value may not be empty!
notNull.message = The value cannot be null!

这样你就可以覆盖以下的默认值:

In this way you are overriding default values for:

javax.validation.constraints.NotEmpty.message
javax.validation.constraints.NotNull.message

如果您需要针对不同字段的特定消息,则消息属性应包含以下格式:[constraintName.Class.field]。例如:

If you require specific message for different fields, your message properties should include them in the following format: [constraintName.Class.field]. For example:

NotEmpty.Vehicle.model = Model cannot be empty!

如果您不包含上面的覆盖值,它将显示默认值或一般覆盖,如notEmpty消息。

If you do not include override values like one above, it will show default value, or general override like notEmpty message.

当然,还有其他方法可以显示验证消息,例如使用Validator实例中出现的ConstraintViolation对象所需的信息。

Of course, there are other ways of showing validation messages, like using information you need from the ConstraintViolation object that comes out of the Validator instance.

希望这有帮助,

这篇关于Thymeleaf:如何在JSR-303批注中使用自定义消息密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆