I have a simple bean with enum
field
public class TestBean{
@Pattern(regexp = \"A|B\") //does not work
private TestEnum testField;
//getter
I'd like to share my working solution:
@Documented
@Constraint(validatedBy = { EnumValueValidator.class })
@Retention(RetentionPolicy.RUNTIME)
@Target({
ElementType.ANNOTATION_TYPE,
ElementType.CONSTRUCTOR,
ElementType.FIELD,
ElementType.METHOD,
ElementType.PARAMETER
})
public @interface EnumValue
{
public abstract String message() default "{validation.enum.message}";
public abstract Class>[] groups() default {};
public abstract Class extends Payload>[] payload() default {};
public abstract Class extends java.lang.Enum>> enumClass();
}
public class EnumValueValidator implements ConstraintValidator
{
private Object[] enumValues;
@Override
public void initialize(final EnumValue annotation)
{
enumValues = annotation.enumClass().getEnumConstants();
}
@Override
public boolean isValid(final Object value, final ConstraintValidatorContext context)
{
if (null != value) {
String contextValue = value.toString();
for (Object enumValue : enumValues) {
if (enumValue.toString().equals(contextValue)) {
return true;
}
}
}
return false;
}