Search code examples
javaenumsannotations

Java String validation using enum values and annotation


I want to validate a string against a set of values using annotations.

What I want is basically this:

@ValidateString(enumClass=com.co.enum)
String dataType;

int maxValue;
int minValue;
int precision;

or

@ValidateString(values={"String","Boolean", "Integer"})
String dataType;

int maxValue;
int minValue;
int precision;


I also want to do some validation on other variables depending upon the value set in dataType:

if (dataType = "String") {
    // maxValue, minValue, precision all should be null or zero
}


I can't think of a way to achieve this by custom annotations.
Somebody please help me.


Solution

  • This is what I did.

    Annotation

    public @interface ValidateString {
    
        String[] acceptedValues();
    
        String message() default "{uk.dds.ideskos.validator.ValidateString.message}";
    
        Class<?>[] groups() default { };
    
        Class<? extends Payload>[] payload() default { }; 
    }
    

    Validation Class

    public class StringValidator implements ConstraintValidator<ValidateString, String>{
    
        private List<String> valueList;
    
        @Override
        public void initialize(ValidateString constraintAnnotation) {
            valueList = new ArrayList<String>();
            for(String val : constraintAnnotation.acceptedValues()) {
                valueList.add(val.toUpperCase());
            }
        }
    
        @Override
        public boolean isValid(String value, ConstraintValidatorContext context) {
            return valueList.contains(value.toUpperCase());
        }
    
    }
    

    And i used it like

    @ValidateString(acceptedValues={"Integer", "String"}, message="Invalid dataType")
    String dataType;
    
    Long maxValue;
    Long minValue;
    

    Now I need to figure out how to implement conditional check ie. if String then maxValue and minValue should be null or Zero..

    Any ideas?