Since for some reason enumerations are not supported, this restriction can simply be handled by a simple String based Validator.
Validator:
public class ValueValidator implements ConstraintValidator<Value, Object> { private String[] values; @Override public void initialize(final Value constraintAnnotation) { this.values = constraintAnnotation.values(); } @Override public boolean isValid(final Object value, final ConstraintValidatorContext context) { return ArrayUtils.contains(this.values, value == null ? null : value.toString()); } }
Interface:
@Target(value = { ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER }) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = { ValueValidator.class }) @Documented public @interface Value { public String message() default "{package.Value.message}"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; public String[] values() default {}; }
The validator uses the apache commons library. The advanced push method method will further increase the flexibility of this validator.
An alternative can use only one String attribute instead of an array and split by separator. It also prints the values ββwell for the error message, since arrays are not printed, but handling null values ββcan be a problem when using String.valueOf(...)
source share