Search code examples
javahibernate-validator

supplying values for a hibernate validator allowing multiple values


I have a Hibernate validator that validates a field against a given list of strings. I will put code for better clarity.

    @Target({ METHOD, FIELD, ANNOTATION_TYPE })
    @Retention(RUNTIME)
    @Constraint(validatedBy = AllowedValuesValidator.class)
    @Documented
    public @interface AllowedValues {
      ...
      String[] value();
    }

Previously we were using it as

  @AllowedValues("value1")
  private String method;

Now we need to use it for a range of values, method can have multiple values. I tried both:

  @AllowedValues("Standard", "One-Day", "Two-Day", "Three-Day")
  private String method;     

and

  @AllowedValues("Standard, One-Day, Two-Day, Three-Day")
  private String method;

First one doesn't compile and second one takes whole string as allowed value(which is obvious).

Any ideas how to specify multiple values here?


Solution

  • Since it's a String[], you need to use array initializer syntax for multiple values:

    @AllowedValues({"Standard", "One-Day", "Two-Day", "Three-Day"})