Hibernate Validator - @Length - How to specify separate message for min and max?

旧城冷巷雨未停 提交于 2019-12-20 10:10:12

问题


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!


回答1:


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. I recommend to prefer @Size as defined by the Bean Validation API over @Length for portability reasons.




回答2:


If you use the java standard javax.validation.constraint.Size, you can achieve the same thing this way:

@Size.List ({
    @Size(min=8, message="The field must be at least {min} characters"),
    @Size(max=60, message="The field must be less than {max} characters")
})
private String myString;

Notice that you can avoid hardcoding the field size by using message interpolation.




回答3:


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"



来源:https://stackoverflow.com/questions/7084706/hibernate-validator-length-how-to-specify-separate-message-for-min-and-max

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!