JSR-303 Bean Validation for enum fields

前端 未结 3 667
南笙
南笙 2021-02-05 19:40

I have a simple bean with enum field

public class TestBean{
   @Pattern(regexp = \"A|B\") //does not work
   private TestEnum testField;
   //getter         


        
3条回答
  •  梦谈多话
    2021-02-05 20:26

    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[]         payload() default {};
    
        public abstract Class> 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;
        }
    

提交回复
热议问题