如何使用javascript验证信用卡到期日期(mm-yy,不得超过当前月份和年份)?

CEz*_*CEz -1 javascript

我知道如何验证日期,但如何验证日期未过期?它应该大于当年。

function validate(){
    var errMsg = "";
    var result = true;
    var visa = document.getElementById("visa").checked;
    var mastercard = document.getElementById("mastercard").checked;
    var american_express = document.getElementById("american_express").checked;
    if(!(visa || mastercard || american_express)){
        errMsg += "please select at least one card type.\n";
        result = false;
    }

    var name = document.getElementById("holder_name").value;
    if(!name.match(/^[a-zA-Z]{1,30}$/)){
        errMsg += "Please enter a name maximum of 30 characters, alphabetical only.\n";
        result = false;
    }

    var cardNumber = document.getElementById("card_number").value;
    if(!cardNumber.match(/\d{15,16}$/)){
        errMsg += "The card number should be 15 or 16 digits!\n";
        result = false;
    }
    else{
        var errorMsg = checkCardWithType(cardNumber);
        if(errorMsg != ""){
            errMsg += errorMsg;
            result = false;
        }
    }

    var expire = document.getElementById("expire").value;
    if(!expire.match(/(0[1-9]|1[0-2])[-][0-9]{2}/)){
        errMsg += "The expire date formate is not correct!\n";
        result = false;
    }

    if(errMsg != ""){
        alert(errMsg);
    }

   return result;
}
Run Code Online (Sandbox Code Playgroud)

Guf*_*ffa 5

获取当前年份和月份,解析输入并比较值:

var expire = document.getElementById("expire").value;
if(!expire.match(/(0[1-9]|1[0-2])[-][0-9]{2}/)){
  errMsg += "The expire date formate is not correct!\n";
  result = false;
} else {
  // get current year and month
  var d = new Date();
  var currentYear = d.getFullYear();
  var currentMonth = d.getMonth() + 1;
  // get parts of the expiration date
  var parts = expire.split('-');
  var year = parseInt(parts[1], 10) + 2000;
  var month = parseInt(parts[0], 10);
  // compare the dates
  if (year < currentYear || (year == currentYear && month < currentMonth)) {
    errMsg += "The expiry date has passed.\n";
    result = false;
  }
}
Run Code Online (Sandbox Code Playgroud)