Created
October 23, 2022 03:54
-
-
Save Abhi-Codes/ad49a3486035a32734a225b04297b893 to your computer and use it in GitHub Desktop.
Custom Annotation
This file contains 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
import java.lang.annotation.Retention; | |
import java.lang.annotation.RetentionPolicy; | |
import java.util.Arrays; | |
import java.util.List; | |
import javax.validation.Constraint; | |
import javax.validation.ConstraintValidator; | |
import javax.validation.ConstraintValidatorContext; | |
import javax.validation.Payload; | |
@Retention(RetentionPolicy.RUNTIME) | |
@Constraint(validatedBy = { ValuesAllowed.Validator.class }) | |
public @interface ValuesAllowed { | |
String message() default "Field value should be from list of "; | |
Class<?>[] groups() default {}; | |
Class<? extends Payload>[] payload() default {}; | |
String propName(); | |
String[] values(); | |
class Validator implements ConstraintValidator<ValuesAllowed, String> { | |
private String propName; | |
private String message; | |
private List<String> allowable; | |
@Override | |
public void initialize(ValuesAllowed requiredIfChecked) { | |
this.propName = requiredIfChecked.propName(); | |
this.message = requiredIfChecked.message(); | |
this.allowable = Arrays.asList(requiredIfChecked.values()); | |
} | |
public boolean isValid(String value, ConstraintValidatorContext context) { | |
Boolean valid = this.allowable.contains(value); | |
if (!Boolean.TRUE.equals(valid)) { | |
context.disableDefaultConstraintViolation(); | |
context.buildConstraintViolationWithTemplate(message.concat(this.allowable.toString())) | |
.addPropertyNode(this.propName).addConstraintViolation(); | |
} | |
return valid; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment