简体   繁体   English

Javascript / angularjs中信用卡到期日验证的正则表达式?

[英]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. 我有一个文本字段,当我在该文本字段中输入信用卡有效期(mm / yy)时,我使用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. 在上面的表达式中,月份验证有效,但一年需要00、12、17。 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. 如果要保证正确性,那么如果使用JavaScript的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")); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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