Javascript中的信用卡预测

我正在编写一个工具,onkeydown将运行输入框中输入的当前值,以检查它是否与4种主要类型的信用卡之一的正则表达式匹配.

我觉得它有点工作,但它是片状的,所以我想弄清楚是什么导致它给出错误的响应(例如,有时它会输出2个值而不是1个).是因为我需要在循环之前设置一个标志变量吗?在匹配正确的卡片后,我只是从循环中穿过物体返回,所以我认为这足够了……

正则表达式的标准是从this site提取的:

>签证:^ 4 [0-9] {12}(?:[0-9] {3})?$所有Visa卡号以4开头.新卡有16位数.旧卡有13个.
>万事达卡:^ 5 [1-5] [0-9] {14} $所有万事达卡号码都以数字51到55开头.所有号码都有16位数字.
>美国运通:^ 3 [47] [0-9] {13} $美国运通卡号码以34或37开头,有15位数字.
>发现:^ 6(?:011 | 5 [0-9] {2})[0-9] {12} $发现卡号以6011或65开头.全部有16位数字.

$(function() {

var $cardNumber = $('#js-cardnumber');

var ccMap = {};

ccMap.cards = {
    'amex': '^3[47][0-9]{13}$','discover': '^6(?:011|5[0-9]{2})[0-9]{12}$','mastercard': '^5[1-5][0-9]{14}$','visa': '^4[0-9]{12}(?:[0-9]{3})?$'
};


$cardNumber.keydown(function() {
for (var cardType in ccMap.cards) {
    if (ccMap.cards.hasOwnProperty(cardType)) {
        var regex = ccMap.cards[cardType];
        if (regex.match($(this).val())) {
            console.log(cardType);
            return;
        }
    }
}
});
});​

Here’s a fiddle

最佳答案
看起来你正在以错误的方式使用正则表达式.

如果要针对正则表达式检查字符串,可以使用字符串的match()方法

string.match(regexp) // returns boolean

你这样做是错误的:

if ( regex.match($(this).val()) ) {

尝试将当前值解释为正则表达式.必须是这样的:

if ( $(this).val().match(regex) ) {

您还可以缓存正则表达式以使脚本更有效:

ccMap.cards = {
    'amex': /^3[47][0-9]{13}$/,// store an actual regexp object,not a string
    // ...

// The way you test changes,Now you're able to use the "test"
// method of the regexp object:
if ( regex.test($(this).val()) ) {

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: <span id=&quot...
jQuery 添加水印 <script src="../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...