Created
June 15, 2016 07:22
-
-
Save robinraju/8cba4fa3b22c34fda3cec73338ca460c to your computer and use it in GitHub Desktop.
Java Annotation for validating ISO country code in the given string
This file contains 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
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.ElementType.PARAMETER; | |
import static java.lang.annotation.RetentionPolicy.RUNTIME; | |
/** | |
* Annotation to validate the ISO Currency code. | |
* | |
* @author Robin Raju | |
*/ | |
@Target({FIELD, PARAMETER}) | |
@Retention(RUNTIME) | |
@Constraint(validatedBy = ValidCurrencyCodeValidator.class) | |
@Documented | |
public @interface ValidCurrencyCode { | |
String message() default "wrong iso code"; | |
Class<?>[] groups() default {}; | |
Class<? extends Payload>[] payload() default {}; | |
boolean optional() default false; | |
} |
This file contains 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
import com.google.common.base.Strings; | |
import javax.validation.ConstraintValidator; | |
import javax.validation.ConstraintValidatorContext; | |
import java.util.Currency; | |
import java.util.Set; | |
public class ValidCurrencyCodeValidator implements ConstraintValidator<ValidCurrencyCode, String> { | |
private Boolean isOptional; | |
@Override | |
public void initialize(ValidCurrencyCode validCurrencyCode) { | |
this.isOptional = validCurrencyCode.optional(); | |
} | |
@Override | |
public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) { | |
boolean containsIsoCode = false; | |
Set<Currency> currencies = Currency.getAvailableCurrencies(); | |
try { | |
containsIsoCode = currencies.contains(Currency.getInstance(value)); | |
}catch(IllegalArgumentException e){ | |
} | |
return isOptional ? (containsIsoCode || (Strings.isNullOrEmpty(value))) : containsIsoCode; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment