Created
November 29, 2022 14:05
-
-
Save Christian-Oette/5e44c15a9c4327b7aca3622ef0fe98ff to your computer and use it in GitHub Desktop.
JSR 303 Country code validator with java locale
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
public class CountryCodeValidator implements ConstraintValidator<ValidIso2CountryCode, String> { | |
private static final Set<String> isoCountries = Locale.getISOCountries(Locale.IsoCountryCode.PART1_ALPHA2); | |
@Override | |
public boolean isValid(String content, ConstraintValidatorContext context) { | |
if (content == null) { | |
setErrorMessage(context, "Country code must not be null"); | |
return false; | |
} | |
boolean contains = isoCountries.contains(content.toUpperCase()); | |
if (!contains) { | |
setErrorMessage(context, "Invalid country code "+content); | |
} | |
return contains; | |
} | |
private void setErrorMessage(ConstraintValidatorContext context, String message) { | |
context.disableDefaultConstraintViolation(); | |
context.buildConstraintViolationWithTemplate(message).addConstraintViolation(); | |
} | |
} |
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
@Retention(RetentionPolicy.RUNTIME) | |
@Constraint(validatedBy = { CountryCodeValidator.class }) | |
public @interface ValidIso2CountryCode { | |
String message() default "iso2 country code invalid"; | |
Class<?>[] groups() default {}; | |
Class<? extends Payload>[] payload() default {}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment