Eric Wilson
Eric Wilson

Reputation: 59355

How to check for a length of 5 or 9 with hibernate validator?

I can validate the length of a String with an annotation like:

@Length(max = 255)

But what if I want to verifiy that the length is either 5 or 9? Can this be done with an annotation?

Upvotes: 4

Views: 396

Answers (2)

Bozho
Bozho

Reputation: 597106

Here's the documentation for implementing custom constraint.

It's fairly simple:

  1. You define your own annotation, with the appropriate attributes
  2. You define the class which will perform the validation
  3. You define validation messages
  4. You use the annotation

So perhaps your annotation might look like:

@Constraint(validatedBy=YourChecker.class)
//other annotations
public @interface AllowedValues {
    int[] value();
}

Upvotes: 3

Brian Deterling
Brian Deterling

Reputation: 13724

Try @Pattern(regex=".{5}|.{9}") (change the dot to another character class if you don't want to match everything.

Upvotes: 6

Related Questions