Spring Validation custom messages - field name

后端 未结 2 577
借酒劲吻你
借酒劲吻你 2020-12-11 23:48

Problem: how to get field name in validation messages in Spring

Is there a way I can access the field name in the ValidationMessages.properties file

2条回答
  •  旧巷少年郎
    2020-12-12 00:41

    As of Bean Validation 1.1 (JSR-349), there is no exposed API that provides the contraint message interpolator the name of the actual property field. If such functionality did exist, there would still be some interpolation step required in order to convert the exposed property email into something meaningful for display purposes, particularly in a multilingual based application.

    The closest you can currently get would be to extend the @NotEmpty annotation and add an attribute to it that allows you to pass the name of the property you desire.

    public class RegistrationForm {
       @NotEmpty(label = "Email Address")
       private String email;
    }
    

    In your resource bundle, your message could use the {label} place holder to represent the attribute from the constraint.

    Of course this won't help the multilingual use case I mentioned above, but it at least gives you the ability to define a label such as First Name for a field you may have defined as firstName.

提交回复
热议问题