Javascript 正则表达式拆分信用卡号

标签 javascript regex

我有一个最多包含 16 位数字的信用卡号,我正在尝试将其分开:例如。 (1234567891234567) 到:(1234 5678 9123 4567)

我仍然是一个相当大的 RegExp 新手,但我有 ^(\d{4})(\d{4})?(\d{4})?(\d{4}) ?

当至少 2 个组 (1234 5678) 正好有 4 个数字时,正则表达式将匹配,但在 (1234 56)

时会失败

如果我添加 {2,4},我会得到像 (1234 56 78) 这样我不想要的东西。

非常感谢任何帮助

更新 1: 目标是在用户输入时将信用卡号分开: 所以 123456 会自动变成:1234 56 等等等等

更新 2: 解释我正在尝试做的事情的最简单方法是在这里:https://stripe.com/docs/tutorials/checkout 并点击Pay with Card,然后在“信用卡”字段中输入,您会看到数字随着您的输入而变化。

最佳答案

我本来打算删除它的,因为我的答案并不是我在这个问题中要找的,但我不能删除它,所以:

我能够通过以下函数创建所需的功能:

(这是一个工作示例:http://jsfiddle.net/7vH6T/)

    var creditcards = { 
        list:[
            {
                brand:          'American Express',
                image:          '/images/creditcards/american-express.png',
                verification:   '^3[47][0-9]',
                separation:     '^([0-9]{4})([0-9]{6})?(?:([0-9]{6})([0-9]{5}))?$',
                hidden:         '**** ****** *[0-9][0-9][0-9][0-9]',
                accepted:       true,
                length:         15
            },
            {
                brand:          'MasterCard',
                image:          '/images/creditcards/mastercard.png',
                verification:   '^5[1-5][0-9]',
                separation:     '^([0-9]{4})([0-9]{4})?([0-9]{4})?([0-9]{4})?$',
                hidden:         '**** **** **** [0-9][0-9][0-9][0-9]',
                accepted:       true,
                length:         16
            },
            {
                brand:          'Visa',
                image:          '/images/creditcards/visa.png',
                verification:   '^4[0-9]',
                separation:     '^([0-9]{4})([0-9]{4})?([0-9]{4})?([0-9]{4})?$',
                hidden:         '**** **** **** [0-9][0-9][0-9][0-9]',
                accepted:       true,
                length:         16
            },
            {
                brand:          'Discover',
                image:          '/images/creditcards/discover.png',
                verification:   '^6(?:011|5[0-9]{2})[0-9]',
                separation:     '^([0-9]{4})([0-9]{4})?([0-9]{4})?([0-9]{4})?$',
                hidden:         '**** **** **** [0-9][0-9][0-9][0-9]',
                accepted:       false,
                length:         16
            },
            {
                brand:          'Diners Club',
                image:          '/images/creditcards/diners-club-international.png',
                verification:   '^3(?:0[0-5]|[68][0-9])[0-9]',
                separation:     '^([0-9]{4})([0-9]{4})?([0-9]{4})?(?:([0-9]{4})([0-9]{4})([0-9]{2}))?$',
                hidden:         '**** **** **[0-9][0-9] [0-9][0-9]',
                accepted:       false,
                length:         14
            },
            {
                brand:          'JCB',
                image:          '/images/creditcards/jcb.png',
                verification:   '^(?:2131|1800|35[0-9]{3})[0-9]',
                separation:     '^([0-9]{4})([0-9]{4})?([0-9]{4})?([0-9]{4})?$',
                hidden:         '**** **** **** [0-9][0-9][0-9][0-9]',
                accepted:       false,
                length:         16
            }
        ], 
        active:null 
    };


  //On Keydown
  $('input[name="creditcard"]').keydown(function(e){


    //Preset Data
    var card = $(this).val().replace(/[^0-9]/g,''),
        trim = $.trim( $(this).val().slice(0,-1) );


    //Find the Credit Card
    for( var i=0; i<creditcards.list.length; i++ ){

      //Check the Type
      if(card.match( new RegExp(creditcards.list[i].verification) )){

        //Set the Active Card
        creditcards.active = i;


        //Add Credit Card Icon
        if( $(this).next('img').length == 0 ){

          //Remove any possible Error
          $(this).next('small').remove();

          //Add the Image
          $(this).after('<img src="'+creditcards.list[i].image+'" alt="'+creditcards.list[i].brand+'" style="height:20px; position:relative; top:5px;" />');

        }


        //If the Credit Card is NOT accepted, Show the Error
        if( !creditcards.list[i].accepted && $(this).nextAll('small').length == 0 ){

          //Show Error
          $(this).next('img').after('<small style="margin-left:5px; color:#F00;">'+'Creditcard Not Accepted'+'</small>');

        }

        //End the Loop
        break;

      }

    }



    //Show Invalid Card
    if( creditcards.active == null && card.length > 4 && $(this).nextAll('small').length == 0 ){

      //Show Error
      $(this).after('<small style="margin-left:5px; color:#F00;">'+'Invalid Credit Card'+'</small>');

    }



    //Preset they Key
    key = creditcards.active !== null? creditcards.active : 1 ;


    //If the Last Character is a String, Remove it
    if( e.keyCode == 8 && trim != $(this).val().slice(0,-1) ){

      //Set the New Value
      $(this).val( trim );

      //Stop from Completing
      e.preventDefault();

      //Return
      return;

    }


    //Limit the Length of the Card, Allow Keys
    if( card.length >= creditcards.list[ key ].length && $.inArray(e.keyCode, [37, 38, 39, 40, 46, 8, 9, 27, 13, 110, 190]) === -1 && !e.metaKey && !e.ctrlKey ){
      e.preventDefault();
      return;
    }

    //Add a Space if the Regex Passes
    if( new RegExp(creditcards.list[ key ].separation).exec( card ) && e.keyCode >= 48 && e.keyCode <= 57 ){
      $(this).val( $(this).val() + ' ' );
    }

    //Return
    return;

  });



























  //On Key up Ensure Card is Validated
  $('input[name="creditcard"]').keyup(function(e){

    //Get the Card
    var card = $(this).val().replace(/[^0-9]/,'');

    //Check if the Card is Active
    if( creditcards.active !== null && !card.match( new RegExp(creditcards.list[ creditcards.active ].verification) ) ){

        //Remove any Existing Error
        $(this).nextAll('small').remove();

        //If Not, Remove the Icon
        $(this).next('img').remove();

        //Set Active to NULL
        creditcards.active = null;

    }else
    if( card.length < 4 ){

      //Remove Invalid Card Error
      $(this).next('small').remove();

    }

  });


































  $('input[name="creditcard"]').on('paste',function(e){

    //Save the Element
    var el    = this;

    //Set Timeout to Run Function
    setTimeout(function(){

      //Save the Card
      var card = $(el).val().replace(/[^0-9]/g,'');

      //Remove all but numbers
      $(el).val( card );

      //Prepare the Keydown Event
      var e = jQuery.Event('keydown',{
        which:    37,
        keyCode:  37
      });


      //Trigger Keydown
      $(el).trigger(e).promise().done(function(e){


        //Preset they Key
        key = creditcards.active !== null? creditcards.active : 1 ;

        //Force the Card Length
        card.substr( 0 , creditcards.list[ key ].length );

        //Separate the Card
        var separation  = new RegExp(creditcards.list[ key ].separation).exec( card ),
            storage     = '';

        //Find the Closest Separation Point
        while( !separation && card.length > 1 ){
          storage     = card.charAt( card.length - 1 );
          card        = card.slice(0,-1);
          separation  = new RegExp(creditcards.list[ key ].separation).exec( card );
        }

        //If there was a Separation
        if( separation ){

          //A Holder for all of the Separation that is defined
          var separated = [];

          //Remove all Undefined Separation Fields
          for( var i=0; i<separation.length; i++){
            if( typeof separation[i] != 'undefined' ) separated.push( separation[i] );
          }

          //Build the String
          var string = separated.slice(1).join(' ') + (storage!=''? ' '+storage : '' )

          //Add the Separated Value
          $(el).val( string )

        }        

      //End $(el).trigger(e).promise().dome(function(e){
      });

    //End setTimeout(function(){
    },0);

  //End $(input[name="creditcard"]
  });

关于Javascript 正则表达式拆分信用卡号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25101781/

相关文章:

javascript - 正则表达式检查大写字母或小写字母(如果@在开头使用)

javascript - 忽略 HTML 标签以突出显示匹配的单词

javascript - 结果未显示在自动完成中( Angular )

ruby-on-rails - 事件记录正则表达式

regex - AWS WAF Regexp 问题与前瞻

java - 正则表达式匹配某些模式与换行符

javascript - 棘手的正则表达式捕获

javascript - 使用来自 jQuery (Coffeescript) 的 JSON 响应

javascript - 如何将 4 小时添加到格式化的日期/时间

javascript - 动态CRM2016 : cannot read property 'SetParameter' of undefined