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 d
I take up Rajeev Singla's response https://stackoverflow.com/a/21070806/8923905, just to optimize the code and allow the String parameter to be null, if in your application it is not mandatory and can be empty :
1- Remove the @NotNull annotation on the Interface
2- See the modified code below for the implementation.
public class EnumValidatorImpl implements ConstraintValidator {
private List valueList = null;
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
return null == value || valueList.contains(value.toUpperCase());
}
@Override
public void initialize(EnumValidator constraintAnnotation) {
valueList = new ArrayList<>();
Class extends Enum>> enumClass = constraintAnnotation.enumClass();
Enum[] enumValArr = enumClass.getEnumConstants();
for(Enum enumVal : enumValArr) {
valueList.add(enumVal.toString().toUpperCase());
}
}
}