Reputation: 6084
I have a REST API that takes credit card information as input and processes it. I am using various javax.validation annotations such as @NotNull for validating the mandatory data.
How can I validate the expiry date on a credit card?
Note: Credit Card expiry date does NOT contain date. It contains only month and year. Example: 12/17 which means that the card is expiring in Dec 2107.
public class CreditCardData {
@NotNull
private Long cardNo
@NotNull
//WHAT ANNOTATION SHOULD I PUT HERE SO THAT IT IS FUTURE DATE ?????
//WILL CONTAIN ONLY MON/YY, EXAMPLE: 12/17
private String expiryDate
}
Upvotes: 0
Views: 1379
Reputation: 30285
I don't know of a ready-made annotation that validates card expirations, but it's quite easy to create your own.
Create your annotation:
@Target({ METHOD, FIELD, PARAMETER })
@Retention(RUNTIME)
@Constraint(validatedBy = CardExpirationValidator.class)
public static @interface CardExpiration {
String message() default "Expiration invalid";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Note the javax.validation.Constraint
annotation - it says that the CardExpiration annotation is a constraint validated by another class - CardExpirationValidator.class
. So let's go ahead and write that class with our validation logic. It's going to be something like this:
public static class CardExpirationValidator implements ConstraintValidator<CardExpiration, String> {
@Override
public void initialize(CardExpiration annotation) {
//Not much to do - this is invoked before "isValid", and can be used to pass annotation parameters
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
//Insert validation logic for "value" here. Return true/false
}
}
Now you can annotate parameters and fields like this:
public class CreditCardData {
@NotNull
private Long cardNo;
@NotNull
@CardExpiration
private String expiryDate;
}
See Jersey's/JBoss's documentation on the topic.
Upvotes: 3