javax.validation to validate list of values?

前端 未结 3 735
南笙
南笙 2020-12-28 13:06

is there a way to use javax.validation to validate a variable of type string called colour that needs to have these values only(red, blue, green, pink) using annotations?

3条回答
  •  长发绾君心
    2020-12-28 13:36

    You can create a custom validation annotation. I will write it here (untested code!):

    @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
    @Retention(RUNTIME)
    @Documented
    @Constraint(validatedBy = InConstraintValidator.class)
    public @interface In
    {
        String message() default "YOURPACKAGE.In.message}";
    
        Class[] groups() default { };
    
        Class[] payload() default {};
    
        Object[] values(); // TODO not sure if this is possible, might be restricted to String[]
    }
    
    public class InConstraintValidator implements ConstraintValidator
    {
    
        private Object[] values;
    
        public final void initialize(final In annotation)
        {
            values = annotation.values();
        }
    
        public final boolean isValid(final String value, final ConstraintValidatorContext context)
        {
            if (value == null)
            {
                return true;
            }
            return ...; // check if value is in this.values
        }
    
    }
    

提交回复
热议问题