简体   繁体   中英

Regular expression for Credit Card Expiry date validation in Javascript/angularjs?

I have a textfield, and when I enter credit card expiry date (mm/yy) in that textfield, I validate the date with Javascript. I have tried the following regular expressions:

var s = "11/12";                                                        
/^(0[1-9]|1[0-2])\/\d{2}$/.test(s);

In the above expression, month validation works but it takes 00,12,17 for year. How do I validate year as well?

If you're going for correctness, you could do a much more correct date validation if you used JavaScript's Date API. For instance:

 function validateExpiry (input) { // ensure basic format is correct if (input.match(/^(0\\d|1[0-2])\\/\\d{2}$/)) { const {0: month, 1: year} = input.split("/"); // get midnight of first day of the next month const expiry = new Date("20"+year, month); const current = new Date(); return expiry.getTime() > current.getTime(); } else return false; } console.log("01/23", validateExpiry("01/23")); console.log("01/18", validateExpiry("04/18")); console.log("05/18", validateExpiry("05/18")); console.log("05.18", validateExpiry("05.18")); console.log("invalid", validateExpiry("invalid")); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM