Skip to content

Instantly share code, notes, and snippets.

@Christian-Oette
Created November 29, 2022 14:05
Show Gist options
  • Save Christian-Oette/5e44c15a9c4327b7aca3622ef0fe98ff to your computer and use it in GitHub Desktop.
Save Christian-Oette/5e44c15a9c4327b7aca3622ef0fe98ff to your computer and use it in GitHub Desktop.
JSR 303 Country code validator with java locale
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();
}
}
@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