diff --git a/model/src/main/java/uk/gov/service/payments/commons/api/validation/AllowedStrings.java b/model/src/main/java/uk/gov/service/payments/commons/api/validation/AllowedStrings.java new file mode 100644 index 00000000..c424511e --- /dev/null +++ b/model/src/main/java/uk/gov/service/payments/commons/api/validation/AllowedStrings.java @@ -0,0 +1,33 @@ +package uk.gov.service.payments.commons.api.validation; + +import javax.validation.Constraint; +import javax.validation.Payload; +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +@Target({ FIELD }) +@Retention(RUNTIME) +@Constraint(validatedBy = AllowedStringsValidator.class) +@Documented +public @interface AllowedStrings { + + String message(); + + Class[] groups() default { }; + + Class[] payload() default { }; + + String[] allowed(); + + @Target({ FIELD }) + @Retention(RUNTIME) + @Documented + @interface List { + + AllowedStrings[] value(); + } +} diff --git a/model/src/main/java/uk/gov/service/payments/commons/api/validation/AllowedStringsValidator.java b/model/src/main/java/uk/gov/service/payments/commons/api/validation/AllowedStringsValidator.java new file mode 100644 index 00000000..0f9a9156 --- /dev/null +++ b/model/src/main/java/uk/gov/service/payments/commons/api/validation/AllowedStringsValidator.java @@ -0,0 +1,21 @@ +package uk.gov.service.payments.commons.api.validation; + +import javax.validation.ConstraintValidator; +import javax.validation.ConstraintValidatorContext; +import java.util.Set; + +public class AllowedStringsValidator implements ConstraintValidator { + + private Set allowedStrings; + + @Override + public void initialize(AllowedStrings parameters) { + allowedStrings = Set.of(parameters.allowed()); + } + + @Override + public boolean isValid(String value, ConstraintValidatorContext context) { + if (value == null) return false; + return allowedStrings.contains(value); + } +}