Spring Validation自定义消息 - 字段名称

时间:2015-12-13 10:06:24

标签: spring hibernate validation spring-mvc

问题:如何在Spring中的验证消息中获取字段名称

有没有办法可以访问ValidationMessages.properties文件中的字段名称,例如下面我尝试使用{0},但它不起作用,我已经在某处看到了它。我希望Spring动态地将字段名称放在那里,所以我不必为每个类重复它。

public class RegistrationForm {

    @NotEmpty(message = "{NotEmpty}")
    private String email;


    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

ValidationMessages.properties

NotEmpty={0} TEST

2 个答案:

答案 0 :(得分:1)

如果您使用Spring消息包(即message.properties)而不是ValidationMessages.properties来本地化消息,则可以这样做。

使用您的示例,Spring将(在第一遍中)尝试使用messages.properties中的以下消息键(或代码)本地化字段名称:

[RegistrationForm.email,email]

如果找不到任何内容,则回到字段名称。

然后,

Spring使用以下键查找本地化的错误消息:

[NotEmpty.RegistrationForm.email,NotEmpty.email,NotEmpty.java.lang.String,NotEmpty]

请注意,NotEmpty的优先级高于<{1}} ,因此如果您想根据字段类型自定义消息,请不要上当。。

因此,如果您在java.lang.String,NotEmpty中添加以下内容,您将获得所需的行为:

messages.properties

来自# for the localized field name (or just email as the key) RegistrationForm.email=Registration Email Address # for the localized error message (or use another specific message key) NotEmpty={0} must not be empty! 的javadoc:

  

返回给定字段上验证错误的FieldError参数。   为每个违反的约束调用。   

默认实现返回指示字段名称的第一个参数   (类型为DefaultMessageSourceResolvable,其中“objectName.field”和“field”为代码)。   然后,它添加所有实际约束注释属性(即排除   “message”,“groups”和“payload”)按其属性名称的字母顺序排列。   

可以覆盖到例如从约束描述符中添加更多属性。

使用SpringValidatorAdapter#getArgumentsForConstraint()时,您可以使用ValidationMessages.properties来引用{max}注释的max属性,使用Spring消息包@Size(因为{1}是按字母顺序排序时max的第一个属性。)

有关详细信息,您还可以查看我对ease field name localization的功能请求。

附录:如何查找此信息?

不幸的是踩到代码(现在这个帖子!)。

要找出用于本地化错误字段的密钥,请检查@Size的值。在您的示例中,您将收到此错误:

BindingResult

Field error in object 'RegistrationForm' on field 'email': rejected value []; codes [NotEmpty.RegistrationForm.email,NotEmpty.email,NotEmpty.java.lang.String,NotEmpty]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [RegistrationForm.email,email]; arguments []; default message [email]]; default message [may not be empty] 负责为错误消息提供验证注释属性值和字段名称。

答案 1 :(得分:0)

从Bean Validation 1.1(JSR-349)开始,没有公开的API为约束消息插值器提供实际属性字段的名称。如果确实存在这样的功能,则仍然需要一些插值步骤才能将公开的属性email转换为有意义的用于显示目的,特别是在基于多语言的应用程序中。

您当前可以获得的最接近的是扩展@NotEmpty注释并为其添加一个属性,允许您传递所需属性的名称。

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

在您的资源包中,您的消息可以使用{label}占位符来表示约束中的属性。

当然,这对我上面提到的多语言用例没有帮助,但它至少使您能够为您可能定义为First Name的字段定义firstName等标签。