Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

validate the credit card expiry date using java?

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.

like image 475
Preethi Avatar asked Nov 27 '22 06:11

Preethi


1 Answers

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());

Edited:

Thanks to @ryanp for the leniency aspect. The above code will now throw a ParseException if the input is not proper.

like image 153
Bohemian Avatar answered Dec 01 '22 00:12

Bohemian