Thymeleaf : How to use Custom Message Key in JSR-303 Annotation

微笑、不失礼 提交于 2019-12-05 03:48:41

问题


Use Thymeleaf

Person.java

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

message.properties

Valid.Password = Password is Empty!!

Login.html

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

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

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

how to use custom message key?


回答1:


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;

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

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!

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

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.

Hope this helps,



来源:https://stackoverflow.com/questions/20323655/thymeleaf-how-to-use-custom-message-key-in-jsr-303-annotation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!