Hibernate Validator - @Length - 如何为最小值和最大值指定单独的消息?
我在我的网络应用程序中使用 Hibernate 验证器进行表单验证。我对 String 属性使用 @Length()
注释,如下所示。
@Length(min = 5, message = "The field must be at least 5 characters")
private String myString;
但是,如果字符串超过 50 个字符,我需要显示不同的消息。有没有办法使用开箱即用的@Length验证器来做到这一点?我想做的一个例子(编译器不会让我这样做)如下:
@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 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;
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;
I have tried @Max and @Min and they do not do what I want. Any input would be greatly appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用内部 列表注释(为 Bean Validation/Hibernate Validator 中的每个约束类型定义),如下所示:
顺便说一句。我建议更喜欢 @Size< /a> 由 Bean Validation API 出于可移植性原因通过
@Length
定义。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:Btw. I recommend to prefer @Size as defined by the Bean Validation API over
@Length
for portability reasons.如果您使用 java 标准 javax.validation.constraint.Size,则可以通过以下方式实现相同的效果:
请注意,您可以通过使用消息插值来避免对字段大小进行硬编码。
If you use the java standard javax.validation.constraint.Size, you can achieve the same thing this way:
Notice that you can avoid hardcoding the field size by using message interpolation.
根据文档,您可以将
@Length(min=, max=)
与一条消息一起使用。然后只需将消息更改为“该字段必须介于 5 到 50 个字符之间”According to documentation, you can use
@Length(min=, max=)
, with one message. Then just change your message to "The field must be between 5 and 50 characters"