Javascript 格式化信用卡号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36833366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:37:06  来源:igfitidea点击:

Format credit card number

javascriptphphtml

提问by youv

How to format and validate a credit card number with spaces between each 4 digit while typing:

如何在键入时格式化和验证每 4 位数字之间有空格的信用卡号:

eg: 4464 6846 4354 3564

I have tried:

我试过了:

$('.creditno').keyup(function() {
    cc = $(this).val().split("-").join("");

    cc = cc.match(new RegExp('.{1,4}$|.{1,4}', 'g')).join("-");

    $(this).val(cc);

});

Please help

请帮忙

回答by prava

Try this:

尝试这个:

function cc_format(value) {
    var v = value.replace(/\s+/g, '').replace(/[^0-9]/gi, '')
    var matches = v.match(/\d{4,16}/g);
    var match = matches && matches[0] || ''
    var parts = []

    for (i=0, len=match.length; i<len; i+=4) {
        parts.push(match.substring(i, i+4))
    }

    if (parts.length) {
        return parts.join(' ')
    } else {
        return value
    }
}

Note: Check this for detailed information https://www.peterbe.com/plog/cc-formatter.

注意:查看此以获取详细信息https://www.peterbe.com/plog/cc-formatter

To restrict the user to enter number only:

限制用户只能输入数字:

Javascript Way

Javascript 方式

<input type="text" id="txt_cardNumber" name="txt_cardNumber" onkeypress="return checkDigit(event)">

function checkDigit(event) {
    var code = (event.which) ? event.which : event.keyCode;

    if ((code < 48 || code > 57) && (code > 31)) {
        return false;
    }

    return true;
}

OR

或者

function checkDigit() {
    var allowedChars = "0123456789";
    var entryVal = document.getElementById('txt_cardNumber').value();
    var flag;

    for(var i=0; i<entryVal.length; i++){       
        flag = false;

        for(var j=0; j<allowedChars.length; j++){
            if(entryVal.charAt(i) == allowedChars.charAt(j)) {
                flag = true; 
            }
        }

        if(flag == false) { 
            entryVal = entryVal.replace(entryVal.charAt(i),""); i--; 
        }
    }

    return true;
}

HTML5 Way

HTML5方式

<input type="text" id="txt_cardNumber" name="txt_cardNumber" pattern="[0-9.]+">
<input type="number" id="txt_cardNumber" name="txt_cardNumber">

jQuery Way

jQuery方式

$("#txt_cardNumber").keypress(function (e) {
    if ((e.which < 48 || e.which > 57) && (e.which !== 8) && (e.which !== 0)) {
        return false;
    }

    return true;
});

Note: Please check hereto get more information about various key code.

注意:请查看此处以获取有关各种密钥代码的更多信息。

回答by NateS

I couldn't find a reasonable solution that works with text editing, so here you go:

我找不到适用于文本编辑的合理解决方案,所以你去吧:

$("#cardNumber").on("keydown", function(e) {
    var cursor = this.selectionStart;
    if (this.selectionEnd != cursor) return;
    if (e.which == 46) {
        if (this.value[cursor] == " ") this.selectionStart++;
    } else if (e.which == 8) {
        if (cursor && this.value[cursor - 1] == " ") this.selectionEnd--;
    }
}).on("input", function() {
    var value = this.value;
    var cursor = this.selectionStart;
    var matches = value.substring(0, cursor).match(/[^0-9]/g);
    if (matches) cursor -= matches.length;
    value = value.replace(/[^0-9]/g, "").substring(0, 16);
    var formatted = "";
    for (var i=0, n=value.length; i<n; i++) {
        if (i && i % 4 == 0) {
            if (formatted.length <= cursor) cursor++;
            formatted += " ";
        }
        formatted += value[i];
    }
    if (formatted == this.value) return;
    this.value = formatted;
    this.selectionEnd = cursor;
});

The keydownlistener is needed to adjust the cursor position for backspace and delete to move past spaces. It should not be used to restrict character entry, as you don't want to use key codes for that.

keydown监听器需要调整退格键的光标位置和删除搬过去的空间。它不应该用于限制字符输入,因为您不想为此使用键码。

The inputlistener rebuilds the text, strips non-numbers, adds spaces every 4 characters, and preserves the cursor position.

input听者重建文本,剥离非数字,空格增加每4个字符,并保留光标位置。

回答by Robert H

Just wrote this to handle Visa, Discover, Master Card and Amex (with formatting and card type identification).

只是写这个来处理 Visa、Discover、Master Card 和 Amex(带有格式和卡类型识别)。

// SAMPLE FIELD:   <input type="text" name="cstCCNumber" id="cstCCNumber" value=""onkeyup="cc_format('cstCCNumber','cstCCardType');">
    function cc_format(ccid,ctid) {
        // supports Amex, Master Card, Visa, and Discover
        // parameter 1 ccid= id of credit card number field
        // parameter 2 ctid= id of credit card type field

        var ccNumString=document.getElementById(ccid).value;
        ccNumString=ccNumString.replace(/[^0-9]/g, '');
        // mc, starts with - 51 to 55
        // v, starts with - 4
        // dsc, starts with 6011, 622126-622925, 644-649, 65
        // amex, starts with 34 or 37
        var typeCheck = ccNumString.substring(0, 2);
        var cType='';
        var block1='';
        var block2='';
        var block3='';
        var block4='';
        var formatted='';

        if  (typeCheck.length==2) {
            typeCheck=parseInt(typeCheck);
            if (typeCheck >= 40 && typeCheck <= 49) {
                cType='Visa';
            }
            else if (typeCheck >= 51 && typeCheck <= 55) {
                cType='Master Card';
            }
            else if ((typeCheck >= 60 && typeCheck <= 62) || (typeCheck == 64) || (typeCheck == 65)) {
                cType='Discover';
            }
            else if (typeCheck==34 || typeCheck==37) {
                cType='American Express';
            }
            else {
                cType='Invalid';
            }
        }

        // all support card types have a 4 digit firt block
        block1 = ccNumString.substring(0, 4);
        if (block1.length==4) {
            block1=block1 + ' ';
        }

        if (cType == 'Visa' || cType == 'Master Card' || cType == 'Discover') {
            // for 4X4 cards
            block2 = ccNumString.substring(4, 8);
            if (block2.length==4) {
                block2=block2 + ' ';
            }
            block3 = ccNumString.substring(8, 12);
            if (block3.length==4) {
                block3=block3 + ' ';
            }
            block4 = ccNumString.substring(12, 16);
        }
        else if (cType == 'American Express') {
            // for Amex cards
            block2 =  ccNumString.substring(4, 10);
            if (block2.length==6) {
                block2=block2 + ' ';
            }
            block3 =  ccNumString.substring(10, 15);
            block4='';
        }
        else if (cType == 'Invalid') {
            // for Amex cards
            block1 =  typeCheck;
            block2='';
            block3='';
            block4='';
            alert('Invalid Card Number');
        }

        formatted=block1 + block2 + block3 + block4;
        document.getElementById(ccid).value=formatted;
        document.getElementById(ctid).value=cType;
    }

回答by gauravbhai daxini

function cc_format(value) {
  var v = value.replace(/\s+/g, '').replace(/[^0-9]/gi, '')
  var matches = v.match(/\d{4,16}/g);
  var match = matches && matches[0] || ''
  var parts = []
  for (i=0, len=match.length; i<len; i+=4) {
    parts.push(match.substring(i, i+4))
  }
  if (parts.length) {
    return parts.join(' ')
  } else {
    return value
  }
}

onload = function() {
  document.getElementById('cc').oninput = function() {
    this.value = cc_format(this.value)
  }
}
function checkDigit(event) {
    var code = (event.which) ? event.which : event.keyCode;

    if ((code < 48 || code > 57) && (code > 31)) {
        return false;
    }

    return true;
}
<form>
  <input id="cc" value="" placeholder="1234 1234 1234 1234" onkeypress="return checkDigit(event)">
</form>

Live demo of check digit and formatting of CC card number

CC卡号校验位及格式化现场演示

回答by Sagar Bhosale

Find

Plunker for Formatting Credit Card Numbers

用于格式化信用卡号的Plunker

using angularjs directive. Format Card Numbers in xxxxxxxxxxxx3456 Fromat.

使用 angularjs 指令。以 xxxxxxxxxxxx3456 Fromat 格式格式化卡号。

angular.module('myApp', [])

   .directive('maskInput', function() {
    return {
            require: "ngModel",
            restrict: "AE",
            scope: {
                ngModel: '=',
             },
            link: function(scope, elem, attrs) {
                var orig = scope.ngModel;
                var edited = orig;
                scope.ngModel = edited.slice(4).replace(/\d/g, 'x') + edited.slice(-4);

                elem.bind("blur", function() {
                    var temp;
                    orig  = elem.val();
                    temp = elem.val();
                    elem.val(temp.slice(4).replace(/\d/g, 'x') + temp.slice(-4));
                });

                elem.bind("focus", function() {
                    elem.val(orig);
               });  
            }
       };
   })
  .controller('myCtrl', ['$scope', '$interval', function($scope, $interval) {
    $scope.creditCardNumber = "1234567890123456";
  }]);

回答by Juliano Reis

With ES6

使用 ES6

export const formatCardNumber = value => {
  const regex = /^(\d{0,4})(\d{0,4})(\d{0,4})(\d{0,4})$/g
  const onlyNumbers = value.replace(/[^\d]/g, '')

  return onlyNumbers.replace(regex, (regex, , , , ) =>
    [, , , ].filter(group => !!group).join(' ')
  )
}

回答by Waruna Manjula

<?php


function luhn_check($number) {

  // Strip any non-digits (useful for credit card numbers with spaces and hyphens)
  $number=preg_replace('/\D/', '', $number);

  // Set the string length and parity
  $number_length=strlen($number);
  $parity=$number_length % 2;

  // Loop through each digit and do the maths
  $total=0;
  for ($i=0; $i<$number_length; $i++) {
    $digit=$number[$i];
    // Multiply alternate digits by two
    if ($i % 2 == $parity) {
      $digit*=2;
      // If the sum is two digits, add them together (in effect)
      if ($digit > 9) {
        $digit-=9;
      }
    }
    // Total up the digits
    $total+=$digit;
  }

  // If the total mod 10 equals 0, the number is valid
  return ($total % 10 == 0) ? TRUE : FALSE;

}
?>

回答by Bhanu

function testCreditCard () {
  myCardNo = document.getElementById('CardNumber').value;
  myCardType = document.getElementById('CardType').value;
  if (checkCreditCard (myCardNo,myCardType)) {
    alert ("Credit card has a valid format")
  } 
  else {alert (ccErrors[ccErrorNo])};
}

check this link for lib http://www.braemoor.co.uk/software/creditcard.shtml

检查此链接以获取 lib http://www.braemoor.co.uk/software/creditcard.shtml

回答by Russell Chisholm

using vanilla js

使用香草js

javascript:

javascript:

function formatCreditCardOnKey(event) {
    //on keyup, check for backspace to skip processing
    var code = (event.which) ? event.which : event.keyCode;
    if(code != 8)
        formatCreditCard();
    else{
        //trim whitespace from end; trimEnd() doesn't work in IE
        document.getElementById("cardNumber").value = document.getElementById("cardNumber").value.replace(/\s+$/, '');
    }

}

function formatCreditCard() {
    var cardField = document.getElementById("cardNumber");
    //remove all non-numeric characters
    var realNumber = cardField.value.replace(/\D/g,'');
    var newNumber = "";
    for(var x = 1; x <= realNumber.length; x++){
        //make sure input is a digit
        if (isNumeric(realNumber.charAt(x-1)))
            newNumber += realNumber.charAt(x-1);
        //add space every 4 numeric digits
        if(x % 4 == 0 && x > 0 && x < 15)
            newNumber += " ";
    }
    cardField.value = newNumber;
}

function isNumeric(char){
    return('0123456789'.indexOf(char) !== -1);
}

HTML:

HTML:

<input type="text" id="cardNumber" maxlength="19" onKeyUp="formatCreditCardOnKey(event)" onBlur="formatCreditCard()" onFocus="formatCreditCard()"/>

This works (for me) with autofill, allows the user to use backspace as expected (they don't have to delete whitespace), and doesn't allow (other) non-numeric characters.

这适用于(对我而言)自动填充,允许用户按预期使用退格(他们不必删除空格),并且不允许(其他)非数字字符。

回答by ravi

Format credit card number will be 16 digits and having automatic spacing between them will get by trying the below code for me. try it once

格式化信用卡号码将是 16 位数字,并且通过为我尝试以下代码将获得它们之间的自动间距。尝试一次

handlecard(text) {
    let formattedText = text.split(' ').join('');
    if (formattedText.length <= 16) {
      if (formattedText.length > 0) {
        formattedText = formattedText.match(new RegExp('.{1,4}', 'g')).join(' ');
      }
    } else {
      alert("plz stop here")
    }
    this.setState({ creditCard: formattedText });
    return formattedText;
  }