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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With