【问题标题】:Validating credit card expiry date against todays date in JavaScript在 JavaScript 中根据今天的日期验证信用卡到期日期
【发布时间】:2017-04-27 03:29:29
【问题描述】:

我正在为学校处理一项任务,我们正在使用 JavaScript(我只能使用 JavaScript)来验证支付页面的表单。这是我第一次使用 JavaScript,所以我感到有点失落......

我面临验证到期日期的任务,要求是:

  1. 数字必须是 2-2 位数字(格式为 mm-yy)
  2. mm 需要 >01 和
  3. 并且到期日期必须在今天之后

到目前为止,我只能指定前两个要求,并且无法弄清楚如何根据今天的日期检查日期。

html

<form>
<label for="expiryDate">Expiry Date</label>
<input type="text" name="expiryDate" id="expiryDate" />

<input type="submit" value="Check out" />
</form>

JavaScript

var expiryDate = document.getElementById("expiryDate").value;

if (!expiryDate.match(/^[0][1-9]|[1][0-2]-[0-9]{2}$/)){
    errMsg = errMsg + "The expiry date needs to be mm-yy and consist of a valid date.\n";
    result = false;
} 

因此,如果有人知道如何帮助我,我将不胜感激!

【问题讨论】:

  • 请注意,您的正则表达式将匹配 "99-12" 之类的值。无论如何,就获取当前日期的月份和年份而言,您是否查看过Date 对象的方法,例如.getMonth() 和.getFullYear()?
  • 我不知道为什么有些人坚持两位数的月份,1-18 应该是完全有效的。为什么要强制用户添加前导零?

标签: javascript date


【解决方案1】:

我总是惊讶于程序员宁愿花精力为用户构建直筒夹克而不是编写用户友好的代码。

月份标准似乎不正确,“>01 和 =1 和

要完全按照作业的要求进行操作,您可以执行以下操作:

/* Check that the provided string is:
**  - exactly 2-2 digits in the format mm-yy
**  - mm is >= 01 and <= 12
**  - expiry date is this month or later
*/
function validateExpiryDate(s) {

  // Check 2-2 digits
  if (!/\d\d-\d\d/.test(s)) {
    return 'Expiry date format must be MM-YY: ' + s;
  }
  
  // Check month is 1 to 12 inclusive
  var b = s.split('-');
  if (b[0]<1 || b[0]>12) {
    return 'Expiry month must be from 00 to 12: ' + b[0];
  }
  
  // Check is this month or later
  var d = new Date()
  var c = d.getFullYear()/100 | 0 + '';
  if (new Date(c + b[1], b[0], 1) < d) {
    return 'Expiry date must be this month or later: ' + s;
  }
  
  return true;
}

// Some tests
['01-17','12-17','foo','13-20','9-18'].forEach(function(s){
  console.log(validateExpiryDate(s));
})

但是,为了更加用户友好,您可以很容易地接受单个数字和各种分隔符。此外,您可以切入正题并测试输入的值是否会生成合适的到期日期。您还可以将输入的字符串重新格式化为所需的格式,例如:

// Validate expiry date in m-yy format
// Separator can be any non-digit
function checkExpiryDate(s) {
  var b = s.split(/\D/);
  var d = new Date();
  var century = d.getFullYear()/100 | 0;
  // Generate date for first day of following month
  var expires = new Date(century + b[1], b[0], 1);
  return d < expires;
}

// Reformat date in m/yy format to mm-yy strict
function formatExpiry(s) {
  var b = s.split(/\D/);
  function z(n){return (n<10?'0':'') + +n}
  return z(b[0]) + '-' + z(b[1]);
}

['1/1','4-17','03-17','3-18','06/19','3.19','foo'].forEach(function(s) {
  console.log('String "' + s + '" converts to "' + 
               formatExpiry(s) + '" and is ' + 
               (checkExpiryDate(s)? '' : 'not ') + 'valid.');
});

因此,用户友好也需要编写更少的代码。 ;-)

计算世纪有点矫枉过正,您可以只使用“20”并期望您的代码不会在 2095 年运行,因为到期日期将开始具有“21”的世纪。

【讨论】:

    【解决方案2】:

    这样的事情应该会有所帮助

    var today = new Date(); // gets the current date
    var today_mm = today.getMonth() + 1; // extracts the month portion
    var today_yy = today.getFullYear() % 100; // extracts the year portion and changes it from yyyy to yy format
    
    if(today_mm < 10) { // if today's month is less than 10
        today_mm = '0' + today_mm // prefix it with a '0' to make it 2 digits
    } 
    
    var mm = expiryDate.substring(0, 2); // get the mm portion of the expiryDate (first two characters)
    var yy = expiryDate.substring(3); // get the yy portion of the expiryDate (from index 3 to end)
    
    if (yy > today_yy || (yy == today_yy && mm >= today_mm)) {
       // all good because the yy from expiryDate is greater than the current yy
       // or if the yy from expiryDate is the same as the current yy but the mm
       // from expiryDate is greater than the current mm
    }
    else
    {
       errMsg = errMsg + "The expiry date needs to be greater than today.\n";
       result = false;
    }
    

    【讨论】:

    • 你也可以连接每个 yymm ...然后检查 yymm >= today_yymm :p
    • 感谢您的回复!我仍然没有完全理解它......这可能是有史以来最简单的事情(但我以前从未做过任何编程,所以我不知道......),但我不知道代码在哪里把那个?是否应该将其作为新语句单独放置.. 或者应该将其放置在此“if (!expiryDate.match(/^[0-9]{2}-[0][1-9]|[1] [0-2]$/)){ errMsg = errMsg + "到期日期必须是 mm-yy 并且包含有效日期。\n"; result = false; }" 不知何故?
    • @SaraBjörkqvist 正如你所说,你已经对前两个要求实施了检查,我的回答只是解决第三个检查。所以你可以把它放在你现有的 javascript 代码之后。
    • @SaraBjörkqvist 我将编辑我的答案以包括其他 cmets 来解释正在发生的事情
    猜你喜欢
    • 2023-03-18
    • 2014-08-14
    • 1970-01-01
    • 1970-01-01
    • 2019-10-16
    • 1970-01-01
    • 2012-07-16
    • 1970-01-01
    相关资源
    最近更新 更多