JSR-303 Bean Validation for enum fields

前端 未结 3 668
南笙
南笙 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:28

    Since for some reasons enumerations are not supported this restriction could be simply handled by a simple String based Validator.

    Validator:

    /**
     * Validates a given object's String representation to match one of the provided
     * values.
     */
    public class ValueValidator implements ConstraintValidator
    {
        /**
         * String array of possible enum values
         */
        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[] payload() default
        {};
    
        public String[] values() default
        {};
    }
    

    Validator uses apache commons library. An advanced coerce to type method would enhance the flexibility of this validator even further.

    An alternative could use a single String attribute instead of an array and split by delimiter. This would also print values nicely for error-message since arrays are not being printed, but handling null values could be a problem using String.valueOf(...)

提交回复
热议问题