I am looking to validate the credit card expiry date in MM/YY format . I have no clue on how to validate , whether to go for Simple date format / Regex .
Appreciate your help.
I am looking to validate the credit card expiry date in MM/YY format . I have no clue on how to validate , whether to go for Simple date format / Regex .
Appreciate your help.
Use SimpleDateFormat
to parse a Date
, then compare it with a new Date
, which is "now":
String input = "11/12"; // for example
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/yy");
simpleDateFormat.setLenient(false);
Date expiry = simpleDateFormat.parse(input);
boolean expired = expiry.before(new Date());
Thanks to @ryanp
for the leniency aspect. The above code will now throw a ParseException
if the input is not proper.
Playing devil's advocate...
boolean validateCardExpiryDate(String expiryDate) {
return expiryDate.matches("(?:0[1-9]|1[0-2])/[0-9]{2}");
}
which translates as:
...so this version requires zero-padded months (01 - 12). Add a ?
after the first 0
to prevent this.
To validate whether you’ve got a valid expiration date string:
DateTimeFormatter ccMonthFormatter = DateTimeFormatter.ofPattern("MM/uu");
String creditCardExpiryDateString = "11/21";
try {
YearMonth lastValidMonth = YearMonth.parse(creditCardExpiryDateString, ccMonthFormatter);
} catch (DateTimeParseException dtpe) {
System.out.println("Not a valid expiry date: " + creditCardExpiryDateString);
}
To validate whether it denotes an expired credit card:
if (YearMonth.now(ZoneId.systemDefault()).isAfter(lastValidMonth)) {
System.out.println("Credit card has expired");
}
Think about which time zone you want to use since the new month doesn’t begin at the same moment in all time zones. If you wanted UTC:
if (YearMonth.now(ZoneOffset.UTC).isAfter(lastValidMonth)) {
If you wanted, for the sake of the example, Europe/Kiev time zone:
if (YearMonth.now(ZoneId.of("Europe/Kiev")).isAfter(lastValidMonth)) {
Link: Oracle tutorial: Date Time explaining how to use java.time.
Do you really need to use regex? Regex is really only suitable for matching characters, not dates. I think it would be far easier to just use simple date functions.
I think that code will be better:
int month = 11;
int year = 2012;
int totalMonth = (year * 12) + month;
totalMonth++; // next month needed
int nextMonth = totalMonth % 12;
int yearOfNextMonth = totalMonth / 12;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/yyyy");
simpleDateFormat.setLenient(false);
Date expiry = simpleDateFormat.parse(nextMonth + "/" + yearOfNextMonth);
boolean expired = expiry.before(new Date());
You need calculate next month because month displayed on credit card is the last month when card is valid.