Skip to content

Commit 609ff79

Browse files
authored
bau: Move AllowedString constraint to pay-java-commons (#936)
Moving from pay-connector as this validator would be useful for other java projects.
1 parent 89cdb51 commit 609ff79

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package uk.gov.service.payments.commons.api.validation;
2+
3+
import javax.validation.Constraint;
4+
import javax.validation.Payload;
5+
import java.lang.annotation.Documented;
6+
import java.lang.annotation.Retention;
7+
import java.lang.annotation.Target;
8+
9+
import static java.lang.annotation.ElementType.FIELD;
10+
import static java.lang.annotation.RetentionPolicy.RUNTIME;
11+
12+
@Target({ FIELD })
13+
@Retention(RUNTIME)
14+
@Constraint(validatedBy = AllowedStringsValidator.class)
15+
@Documented
16+
public @interface AllowedStrings {
17+
18+
String message();
19+
20+
Class<?>[] groups() default { };
21+
22+
Class<? extends Payload>[] payload() default { };
23+
24+
String[] allowed();
25+
26+
@Target({ FIELD })
27+
@Retention(RUNTIME)
28+
@Documented
29+
@interface List {
30+
31+
AllowedStrings[] value();
32+
}
33+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package uk.gov.service.payments.commons.api.validation;
2+
3+
import javax.validation.ConstraintValidator;
4+
import javax.validation.ConstraintValidatorContext;
5+
import java.util.Set;
6+
7+
public class AllowedStringsValidator implements ConstraintValidator<AllowedStrings, String> {
8+
9+
private Set<String> allowedStrings;
10+
11+
@Override
12+
public void initialize(AllowedStrings parameters) {
13+
allowedStrings = Set.of(parameters.allowed());
14+
}
15+
16+
@Override
17+
public boolean isValid(String value, ConstraintValidatorContext context) {
18+
if (value == null) return false;
19+
return allowedStrings.contains(value);
20+
}
21+
}

0 commit comments

Comments
 (0)