Spring验证自定义消息 - 字段名称 [英] Spring Validation custom messages - field name

查看:252
本文介绍了Spring验证自定义消息 - 字段名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:如何在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;


$ / code>

ValidationMessages.properties

  NotEmpty = {0} TEST 


解决方案

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



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

  [RegistrationForm.email ,电子邮件] 

如果找不到任何内容, b

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

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

请注意, code> NotEmpty 更高 p而不是 java.lang.String,NotEmpty ,所以如果你想根据字段类型自定义消息,就不要被愚弄。



因此,如果将以下内容放入 messages.properties 中,您将获得所需的行为:

 #用于本地化字段名称(或者只是电子邮件作为键)
RegistrationForm.email =注册电子邮件地址
#用于本地化错误消息(或使用其他特定的消息密钥)
NotEmpty = {0}不能为空!

来自的Spring类型SpringValidatorAdapter#getArgumentsForConstraint()


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

默认实现返回第一个参数,指示字段名称
(类型为DefaultMessageSourceResolvable,带有objectName.field和field作为代码)。
之后,它以属性名称的字母顺序添加了所有实际的约束注释属性(即不包括
消息,组和有效载荷)。

可以覆盖到例如


使用 ValidationMessages.properties 来添加更多的属性将使用 {max} 来引用 @Size max 属性c $ c>注释,使用Spring消息包将使用 {1} (因为 max 是第一个属性 @Size 按字母顺序排列)。

有关更多信息,还可以查看我的功能请求简化字段名称本地化

附录:如何找到这个信息?

不幸地加入代码(现在这个帖子!)。

到找出哪些键用于本地化错误字段,检查 BindingResult 的值。在你的例子中,你会得到这个错误:

 字段'email'的对象'RegistrationForm'中的字段错误:被拒绝的值[ ]。代码[NotEmpty.RegistrationForm.email,NotEmpty.email,NotEmpty.java.lang.String,NotEmpty];参数[org.springframework.context.support.DefaultMessageSourceResolvable:codes [RegistrationForm.email,email];参数[];默认邮件[email]];默认消息[不能为空] 

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


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, for example below I tried using {0} but it doesn't work, I've seen it somewhere. I want Spring to dynamically put the field name there so I don't have to repeat it for every class.

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

解决方案

This is possible if you use the Spring message bundles (i.e. message.properties) instead of ValidationMessages.properties to localize messages.

Using your example, Spring will (in a first pass) try to localize the field name using the following message keys (or codes) in messages.properties:

[RegistrationForm.email,email]

falling back to the field name if nothing is found.

Spring then looks up the localized error message itself using the following keys:

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

Note here that NotEmpty has higher priority than java.lang.String,NotEmpty so don't get fooled if you want to customize the message based on the field type.

So if you put the following content in your messages.properties, you'll get the desired behavior:

# 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!

From the javadoc of SpringValidatorAdapter#getArgumentsForConstraint():

Return FieldError arguments for a validation error on the given field. Invoked for each violated constraint.

The default implementation returns a first argument indicating the field name (of type DefaultMessageSourceResolvable, with "objectName.field" and "field" as codes). Afterwards, it adds all actual constraint annotation attributes (i.e. excluding "message", "groups" and "payload") in alphabetical order of their attribute names.

Can be overridden to e.g. add further attributes from the constraint descriptor.

While with ValidationMessages.properties you would use {max} to refer to the max attribute of a @Size annotation, with Spring message bundles you would use {1} (because max is the first attribute of @Size when ordered alphabetically).

For more information, you can also see my feature request to ease field name localization.

Appendix: how to find this info?

By stepping in code unfortunately (and this post now!).

To find out which keys are used for localizing the fields the errors, inspect the value of your BindingResult. In your example, you would get this error:

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]

SpringValidatorAdapter#getArgumentsForConstraint() takes care of making the validation annotation attributes values and the field name available for the error message.

这篇关于Spring验证自定义消息 - 字段名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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