2014-06-04 26 views
0

我正在學習AngularJS,我正在製作一個信用卡驗證器。 我已經在自定義過濾器中實現了Luhn算法,並且它完美地工作。但是,爲了驗證表單我想也過期日期是有效的,即滿足這些條件: - 08/16 - 02/2015 - 0518 - 日期不應到期(顯然)AngularJS - 信用卡驗證表格的有效日期格式

因此,由於我發現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.

回答

0

你的過濾器功能概念(雖然你兩個月解釋是關閉的一個,一下就Date構造文檔)。你的問題正在適應它的角度期望。

而不是接收一個單一的日期字符串,正如你在這裏所假設的,你實際上得到了需要過濾的完整數組。而不是返回true/false,你需要返回修改過的數組。

但是,您所寫的功能與Array.prototype.filter非常匹配,所以它在this plunker的作品中解決了我的問題。

下面是相關的更改:

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); 
    }; 
}]); 
+0

謝謝!所以基本上我有邏輯,我只是​​沒有正確使用Angular:我搞砸了過濾驗證。非常感謝 ! –