2015-06-12 65 views
3

我正在寻找一些正确的方法来使用验证消息中的属性名称,如{min}{regexp}javax.validation如何在验证消息中获取属性名称

我已经GOOGLE了这个问题几次,并且显然没有一个本地方法来做到这一点。

@NotNull(message = "The property {propertyName} may not be null.") 
private String property; 

有人能帮助我吗?

更新1

使用自定义消息插值应该是这样的:

public class CustomMessageInterpolator implements MessageInterpolator { 

    @Override 
    public String interpolate(String templateString, Context cntxt) { 

     return templateString.replace("{propertyName}", getPropertyName(cntxt)); 
    } 

    @Override 
    public String interpolate(String templateString, Context cntxt, Locale locale) { 
     return templateString.replace("{propertyName}", getPropertyName(cntxt)); 
    } 

    private String getPropertyName(Context cntxt) { 
     //TODO: 
     return ""; 
    } 
} 
+0

你总是可以编写检查空值,并采取某些属性的自定义注释。 –

+0

当然,我想过这个,但不能肯定是否是最好的选择。一旦是不是检查一个新的注释null值。我正在考虑创建通用消息的一些方法,以防止为每个属性创建一组验证消息。我已阅读了MessageInterpolator接口,但仍不知如何使用它。 –

回答

3

一种解决方案是使用两条消息,夹在中间的属性名称:

@NotBlank(message = "{error.notblank.part1of2}Address Line 1{error.notblank.part2of2}") 
private String addressLineOne; 

然后在您的留言资源文件中:

error.notblank.part1of2=The following field must be supplied: ' 
error.notblank.part2of2='. Correct and resubmit. 

验证失败时,它会生成消息“必须提供以下字段:'地址行1'。正确并重新提交。”

+0

好的解决方案。 显然,在MessageInterpolator.Context中没有办法拦截属性名称,无论如何,谢谢大家,你的回答和评论如果我找到这种性质的解决方案,我会与你分享。 –