Hibernate Validator - @Length - 如何为min和max指定单独的消息? [英] Hibernate Validator - @Length - How to specify separate message for min and max?
问题描述
我在我的网络应用程序中使用Hibernate验证器进行表单验证。我在我的String属性中使用@Length注释,如下所示:
I am using Hibernate validator for form validation in my web-app. I am using the @Length annotation for my String attribute as follows:
@Length(min = 5, message = "The field must be at least 5 characters")
private String myString;
但是,如果字符串超过50个字符,我需要显示不同的消息。有没有办法使用开箱即用的@Length验证器来做到这一点?我想做的一个例子(编译器不会让我)如下:
However, I have a need to display a different message if the String exceeds 50 characters. Is there a way to use the out-of-the-box @Length validator to do this? An example of what I would like to do (compiler will not let me) is as follows:
@Length(min = 5, message = "The field must be at least 5 characters")
@Length(max = 50, message = "The field must be less than 50 characters")
private String myString;
我试过@Max和@Min,他们没有做我想做的事。任何输入都将非常感谢!
I have tried @Max and @Min and they do not do what I want. Any input would be greatly appreciated!
推荐答案
您可以指定几个 @Length
使用内部 list annotation (为Bean Validation / Hibernate Validator中的每个约束类型定义),如下所示:
You can specify several @Length
constraints at one element by using the inner list annotation (which is defined for each constraint type in Bean Validation/Hibernate Validator) like this:
@List({
@Length(min = 5, message = "The field must be at least 5 characters"),
@Length(max = 50, message = "The field must be less than 50 characters")
})
private String myString;
Btw。我建议您更喜欢 @Size 由Bean Validation API在 @Length
上定义,以实现可移植性。
Btw. I recommend to prefer @Size as defined by the Bean Validation API over @Length
for portability reasons.
这篇关于Hibernate Validator - @Length - 如何为min和max指定单独的消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!