Skip to content

Commit

Permalink
bau: Move AllowedString constraint to pay-java-commons (#936)
Browse files Browse the repository at this point in the history
Moving from pay-connector as this validator would be useful for other java
projects.
  • Loading branch information
oswaldquek authored Sep 18, 2024
1 parent 89cdb51 commit 609ff79
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -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<? extends Payload>[] payload() default { };

String[] allowed();

@Target({ FIELD })
@Retention(RUNTIME)
@Documented
@interface List {

AllowedStrings[] value();
}
}
Original file line number Diff line number Diff line change
@@ -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<AllowedStrings, String> {

private Set<String> 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);
}
}

0 comments on commit 609ff79

Please sign in to comment.