开发者

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

I am using Hibernate validator for form validation in my web-app. I am using the @Length annotation for my String attribute as follows:

@Len开发者_开发技巧gth(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!


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.


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.


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"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜