Created
October 24, 2019 16:04
-
-
Save Kapcash/d69deb8d123882cf7e34c35552acf91d to your computer and use it in GitHub Desktop.
Java Spring validator decorator to restreint possibles values from Enum
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Target({ FIELD }) | |
@Retention(RUNTIME) | |
@Documented | |
@Constraint(validatedBy = { EnumRestreintValidator.class }) | |
public @interface EnumRestreint { | |
String message() default "The enum value is not included in the possibles values."; | |
String[] authorizedFields() default {}; | |
Class<?>[] groups() default {}; | |
Class<? extends Payload>[] payload() default {}; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Restreint possibles values from Enum | |
* @author Florent Catiau-Tristant <[email protected]> | |
*/ | |
public class EnumRestreintValidator implements ConstraintValidator<EnumRestreint, Enum<?>> { | |
/** The possible values you can pick from the parameterized enum */ | |
Set<String> validFields; | |
@Override | |
public void initialize(EnumRestreint constraint) { | |
validFields = Arrays.stream(constraint.authorizedFields()).collect(Collectors.toSet()); | |
} | |
@Override | |
public boolean isValid(Enum<?> enumValue, ConstraintValidatorContext constraintValidatorContext) { | |
return validFields.contains(enumValue.name()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment