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

Gre*_*ack 6 validation spring hibernate 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

ValidationMessages.properties

NotEmpty={0} TEST
Run Code Online (Sandbox Code Playgroud)

ber*_*nie 7

如果您使用 Spring 消息包(即message.properties)而不是ValidationMessages.properties本地化消息,这是可能的。

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

[RegistrationForm.email,email]
Run Code Online (Sandbox Code Playgroud)

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

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

[NotEmpty.RegistrationForm.email,NotEmpty.email,NotEmpty.java.lang.String,NotEmpty]
Run Code Online (Sandbox Code Playgroud)

注意这里的优先NotEmpty高于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!
Run Code Online (Sandbox Code Playgroud)

来自 javadoc SpringValidatorAdapter#getArgumentsForConstraint()

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

默认实现返回第一个参数,指示字段名称(类型为 DefaultMessageSourceResolvable,以“objectName.field”和“field”作为代码)。然后,它按照属性名称的字母顺序添加所有实际约束注释属性(即,排除“消息”、“组”和“有效负载”)。

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

在 with 中,ValidationMessages.properties您将使用{max}来引用注释max的属性@Size,而在 Spring 消息包中,您将使用{1}(因为max是按字母顺序排序时的第一个属性@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]
Run Code Online (Sandbox Code Playgroud)

SpringValidatorAdapter#getArgumentsForConstraint()负责使验证注释属性值和字段名称可用于错误消息。


Nar*_*ros 1

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

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

public class RegistrationForm {
   @NotEmpty(label = "Email Address")
   private String email;
}
Run Code Online (Sandbox Code Playgroud)

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

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