2011-03-07 56 views
10

我發現這個簡單的函數返回的4種最常見的信用卡類型。jQuery的發現信用卡類型

作爲新的jQuery的,什麼樣的jQuery插件我可以使用,以顯示信用卡類型,在一個輸入字段信用卡號碼的用戶類型?

function creditCardTypeFromNumber(num) { 
    // first, sanitize the number by removing all non-digit characters. 
    num = num.replace(/[^\d]/g,''); 
    // now test the number against some regexes to figure out the card type. 
    if (num.match(/^5[1-5]\d{14}$/)) { 
    return 'MasterCard'; 
    } else if (num.match(/^4\d{15}/) || num.match(/^4\d{12}/)) { 
    return 'Visa'; 
    } else if (num.match(/^3[47]\d{13}/)) { 
    return 'AmEx'; 
    } else if (num.match(/^6011\d{12}/)) { 
    return 'Discover'; 
    } 
    return 'UNKNOWN'; 
} 

謝謝!

回答

4
$('#someTextBox').change(function() { 
    $('#someOutput').text(creditCardTypeFromNumber($(this).val())); 
}); 

這將輸出與id="someOutput"當用戶改變在元件id="someTextBox"其文本觸發文本框的結果的一些元件。

+6

'change()'不會被觸發,直到文本輸入失去焦點。當你輸入 – Hussein 2011-03-07 02:58:14

+0

時,使用keyup()代替驗證,我知道它有點老了,但我一直在尋找像這樣的東西。只是想要注意,@丹尼爾A.懷特你需要額外的)在第2行結束;) – stinkysGTI 2014-11-14 18:32:37

0

此外,僅供參考,對this thread (link)答案有一定的正則表達式的其他類型的卡,以及信用卡號碼的真棒解釋。

這裏的,只有火後,便進入了至少6個位數(用於識別卡類型的)的函數:

$('#CardNumber').keyup(function(){ 
    if($(this).val().length >= 6){ 
     cardType = creditCardTypeFromNumber($(this).val()); 
    } 
});