AngularJS -信用卡过期日期格式来验证表单

AngularJS - Credit Card Expiration date format to validate form

本文关键字:验证 表单 格式 日期 信用卡 过期 AngularJS      更新时间:2023-09-26

我正在学习AngularJS,我正在制作一个信用卡验证器。我已经实现了Luhn算法在一个自定义过滤器,它的工作完美。然而,为了验证表单,我也希望到期日期是有效的,即满足这些条件:- - - 08/16- - - 02/2015- 0518-日期不得过期(明显)

所以,自从我发现在Angular中已经有了日期过滤器,我就尝试创建一个。对我来说,这似乎是合乎逻辑的,但它根本行不通。下面是代码:

/**
* validate-expiry-date Module
*
* Validates the date format and that the date is not in the past
*/
angular.module('validate-expiry-date', []).filter('validDate', [function () {
  return function (date) {
    var actualDate = new Date();
    var m,y,d;
    if (/^'d{2}'/'d{2}$/.test(date)) {
        m = date.substring(0, 2);
        y = 20 + date.slice(-2);
        d = new Date(y,m);
        return(actualDate > d);
    }if (/^'d{2}'/'d{4}$/.test(date)) {
        m = date.substring(0, 2);
        y = date.slice(-4);
        d = new Date(y,m);
        return(actualDate > d);
    }else if (/^'d{4}$/.test(date)) {
        m = date.substring(0, 2);
        y = 20 + date.slice(-2);
        d = new Date(y,m);
        return(actualDate > d);
    };
  }
}])
谁能告诉我这是怎么回事?谢谢,b .

您的过滤器函数在概念上(尽管您对月份的解释相差一个,请查阅Date构造函数的文档)。你的问题是让它符合angular的期望。

不是接收单个日期字符串,正如您在这里所假设的那样,您实际上得到了需要过滤的完整数组。而不是返回true/false,您需要返回经过修改(过滤)的数组。

然而,你写的函数非常适合Array.prototype.filter,所以它在我固定的这个柱塞中工作。

以下是相关的修改:

function filterSingleDate(date) {
    var actualDate = new Date();
    var m,y,d;
    if (/^'d{2}'/'d{2}$/.test(date)) {
        m = date.substring(0, 2) - 1;
        y = 20 + date.slice(-2);
        d = new Date(y,m);
    } else if (/^'d{2}'/'d{4}$/.test(date)) {
        m = date.substring(0, 2) - 1;
        y = date.slice(-4);
        d = new Date(y,m);
    } else if (/^'d{4}$/.test(date)) {
        m = date.substring(0, 2) - 1;
        y = 20 + date.slice(-2);
        d = new Date(y,m);
    }
    return actualDate > d;
}
var FilterModule = angular.module('FilterModule', []).filter('validDate', [function () {
  return function (dateList) {
    return dateList.filter(filterSingleDate);
  };
}]);