20

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!

Vy Do
  • 46,709
  • 59
  • 215
  • 313
javagruffian
  • 607
  • 2
  • 7
  • 13

3 Answers3

54

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.

Gunnar
  • 18,095
  • 1
  • 53
  • 73
  • 2
    Note that as of Bean Validation 2.0 / Hibernate Validator 6, you'll be able to specify `@Length` and any other constraint multiple times, without the need for the explicit `@List` annotation. – Gunnar Jan 21 '17 at 17:15
14

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.

Chanoch
  • 563
  • 7
  • 16
8

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"

atrain
  • 9,139
  • 1
  • 36
  • 40
  • Yes, I like this solution, but unfortunately I have a requirement that must be implemented with separate messages. – javagruffian Aug 16 '11 at 20:44
  • 2
    You could create a custom constraint that would check both Min and Max and have separate messages for each: http://docs.jboss.org/hibernate/validator/4.0.1/reference/en/html/validator-customconstraints.html – atrain Aug 16 '11 at 20:56