如何验证信用卡号码

mat*_*att 11 javascript

我只想在javascript中验证信用卡号,我使用正则表达式来表示数字,但我不知道为什么不工作!这是我的功能如下:

function validate_creditcardnumber()
{
    var re16digit = /^\d{16}$/
    if (document.myform.CreditCardNumber.value.search(re16digit) == -1)
        alert("Please enter your 16 digit credit card numbers");
    return false;
}
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激

Mr.*_*ack 18

我希望,以下两个链接有助于解决您的问题.仅供参考,世界上有各种信用卡.所以,你的想法是错的,信用卡有一些格式.请参阅以下链接.第一个是纯Javascript,第二个是使用jQuery.

http://www.braemoor.co.uk/software/creditcard.shtml

https://github.com/iHwy/jQuery-Validation-Extension

演示:

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])
  };
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://www.braemoor.co.uk/software/_private/creditcard.js"></script>

<!-- COPIED THE DEMO CODE FROM THE SOURCE WEBSITE (https://www.braemoor.co.uk/software/creditcard.shtml) -->

<table>
  <tbody>
    <tr>
      <td style="padding-right: 30px;">American Express</td>
      <td>3400 0000 0000 009</td>
    </tr>
    <tr>
      <td>Carte Blanche</td>
      <td>3000 0000 0000 04</td>
    </tr>
    <tr>
      <td>Discover</td>
      <td>6011 0000 0000 0004</td>
    </tr>
    <tr>
      <td>Diners Club</td>
      <td>3852 0000 0232 37</td>
    </tr>
    <tr>
      <td>enRoute</td>
      <td>2014 0000 0000 009</td>
    </tr>
    <tr>
      <td>JCB</td>
      <td>3530 111333300000</td>
    </tr>
    <tr>
      <td>MasterCard</td>
      <td>5500 0000 0000 0004</td>
    </tr>
    <tr>
      <td>Solo</td>
      <td>6334 0000 0000 0004</td>
    </tr>
    <tr>
      <td>Switch</td>
      <td>4903 0100 0000 0009</td>
    </tr>
    <tr>
      <td>Visa</td>
      <td>4111 1111 1111 1111</td>
    </tr>
    <tr>
      <td>Laser</td>
      <td>6304 1000 0000 0008</td>
    </tr>
  </tbody>
</table>
<hr /> Card Number:
<select tabindex="11" id="CardType" style="margin-left: 10px;">
  <option value="AmEx">American Express</option>
  <option value="CarteBlanche">Carte Blanche</option>
  <option value="DinersClub">Diners Club</option>
  <option value="Discover">Discover</option>
  <option value="EnRoute">enRoute</option>
  <option value="JCB">JCB</option>
  <option value="Maestro">Maestro</option>
  <option value="MasterCard">MasterCard</option>
  <option value="Solo">Solo</option>
  <option value="Switch">Switch</option>
  <option value="Visa">Visa</option>
  <option value="VisaElectron">Visa Electron</option>
  <option value="LaserCard">Laser</option>
</select> <input type="text" id="CardNumber" maxlength="24" size="24" style="margin-left: 10px;"> <button id="mybutton" type="button" onclick="testCreditCard();" style="margin-left: 10px; color: #f00;">Check</button>

<p style="color: red; font-size: 10px;"> COPIED THE DEMO CODE FROM TEH SOURCE WEBSITE (https://www.braemoor.co.uk/software/creditcard.shtml) </p>
Run Code Online (Sandbox Code Playgroud)


ale*_*xey 12

您可以使用此代码段使用Luhn算法验证16位数的卡号:

function validateCardNumber(number) {
    var regex = new RegExp("^[0-9]{16}$");
    if (!regex.test(number))
        return false;

    return luhnCheck(number);
}

function luhnCheck(val) {
    var sum = 0;
    for (var i = 0; i < val.length; i++) {
        var intVal = parseInt(val.substr(i, 1));
        if (i % 2 == 0) {
            intVal *= 2;
            if (intVal > 9) {
                intVal = 1 + (intVal % 10);
            }
        }
        sum += intVal;
    }
    return (sum % 10) == 0;
}
Run Code Online (Sandbox Code Playgroud)

  • 我想强调"16位数"部分.如果您在15位数卡(例如和Amex)上尝试此操作,则会失败.被警告! (4认同)

Syn*_*der 11

信用卡号码不是一堆随机数.有一个用于检查它是否正确的表格.

快速谷歌后,我发现这个javascript将检查信用卡号是否有效.

http://javascript.internet.com/forms/credit-card-number-validation.html

URL Broken:Internet archieve:http://web.archive.org/web/20100129174150/http://javascript.internet.com/forms/credit-card-number-validation.html

<!-- TWO STEPS TO INSTALL CREDIT CARD NUMBER VALIDATION:

  1.  Copy the code into the HEAD of your HTML document
  2.  Add the last code into the BODY of your HTML document  -->

<!-- STEP ONE: Paste this code into the HEAD of your HTML document  -->

<HEAD>

  <script type="text/javascript">
    <!--
    /* This script and many more are available free online at
    The JavaScript Source!! http://javascript.internet.com
    Created by: David Leppek :: https://www.azcode.com/Mod10

    Basically, the algorithm takes each digit, from right to left and muliplies each second
    digit by two. If the multiple is two-digits long (i.e.: 6 * 2 = 12) the two digits of
    the multiple are then added together for a new number (1 + 2 = 3). You then add up the
    string of numbers, both unaltered and new values and get a total sum. This sum is then
    divided by 10 and the remainder should be zero if it is a valid credit card. Hense the
    name Mod 10 or Modulus 10.
    */
    function Mod10(ccNumb) {  // v2.0
      var valid = "0123456789"  // Valid digits in a credit card number
      var len = ccNumb.length;  // The length of the submitted cc number
      var iCCN = parseInt(ccNumb);  // Integer of ccNumb
      var sCCN = ccNumb.toString();  // String of ccNumb
      sCCN = sCCN.replace (/^\s+|\s+$/g,'');  // Strip spaces
      var iTotal = 0;  // Integer total set at zero
      var bNum = true;  // By default assume it is a number
      var bResult = false;  // By default assume it is NOT a valid cc
      var temp;  // Temporary variable for parsing string
      var calc;  // Used for calculation of each digit

      // Determine if the ccNumb is in fact all numbers
      for (var j=0; j<len; j++) {
        temp = "" + sCCN.substring(j, j+1);
        if (valid.indexOf(temp) == "-1"){
          bNum = false;
        }
      }

      // If it is NOT a number, you can either alert to the fact, or just pass a failure
      if (!bNum) {
        /* alert("Not a Number"); */
        bResult = false;
      }

      // Determine if it is the proper length
      if ((len == 0) && (bResult)) {  // Nothing, the field is blank AND passed above # check
        bResult = false;
      }
      else { // ccNumb is a number and the proper length - let's
             //  see if it is a valid card number

        if (len >= 15) {  // 15 or 16 for Amex or V/MC
          for (var i=len;i>0;i--) {  // LOOP through the digits of the card
            calc = parseInt(iCCN) % 10;  // Right most digit
            calc = parseInt(calc);  // Assure it is an integer
            iTotal += calc;  // Running total of the card number as we loop - Do Nothing to first digit
            i--;  // Decrement the count - move to the next digit in the card
            iCCN = iCCN / 10;                               // Subtracts right most digit from ccNumb
            calc = parseInt(iCCN) % 10;     // NEXT right most digit
            calc = calc *2;                                 // multiply the digit by two

            // Instead of some screwy method of converting 16 to a string
            // and then parsing 1 and 6 and then adding them to make 7,
            // I use a simple switch statement to change the value
            // of calc2 to 7 if 16 is the multiple.
            switch(calc) {
              case 10: calc = 1; break;  // 5*2=10 & 1+0 = 1
              case 12: calc = 3; break;  // 6*2=12 & 1+2 = 3
              case 14: calc = 5; break;  // 7*2=14 & 1+4 = 5
              case 16: calc = 7; break;  // 8*2=16 & 1+6 = 7
              case 18: calc = 9; break;  // 9*2=18 & 1+8 = 9
              default: calc = calc;      // 4*2= 8 &   8 = 8  - the same for all lower numbers
            }
            iCCN = iCCN / 10;  // Subtracts right most digit from ccNum
            iTotal += calc;  // Running total of the card number as we loop
          } // END OF LOOP

          if ((iTotal%10)==0){  // Check to see if the sum Mod 10 is zero
            bResult = true;  // This IS (or could be) a valid credit card number.
          }
          else {
            bResult = false;  // This could NOT be a valid credit card number
          }
        }
      }

      // Change alert to on-page display or other indication as needed.
      if (bResult) {
        alert("This IS a valid Credit Card Number!");
      }
      if (!bResult) {
        alert("This is NOT a valid Credit Card Number!");
      }
      return bResult; // Return the results
    }
    // -->
  </script>

</HEAD>


<!-- STEP TWO: Copy this code into the BODY of your HTML document  -->

<BODY>

<div align="center">
  <form name="Form1">
    <table width="50%" border="0" cellspacing="0" cellpadding="5">
      <tr>
        <td width="50%" align="right">Credit Card Number:   </td>
        <td width="50%">
          <input name="CreditCard" type="text" value="4012888888881881" size="18" maxlength="16" style="border: 1px solid #000098; padding: 3px;">
        </td>
      </tr>
      <tr>
        <td colspan="2" align="center">
          <input type="button" name="Button" style="color: #fff; background: #000098; font-weight:bold; border: solid 1px #000;" value="TEST CARD NUMBER" onClick="return Mod10(document.Form1.CreditCard.value);">
        </td>
      </tr>
    </table>
  </form>
</div>

<p><center>
  <font face="arial, helvetica" size"-2">Free JavaScripts provided<br>
  by <a href="http://javascriptsource.com">The JavaScript Source</a></font>
</center><p>

<!-- Script Size:  4.97 KB -->
Run Code Online (Sandbox Code Playgroud)


ext*_*mpl 10

http://www.w3resource.com/javascript/form/credit-card-validation.php + Luhn算法:

var checkLuhn = function (cardNo) {
    var s = 0;
    var doubleDigit = false;
    for (var i = cardNo.length - 1; i >= 0; i--) {
        var digit = +cardNo[i];
        if (doubleDigit) {
            digit *= 2;
            if (digit > 9)
                digit -= 9;
        }
        s += digit;
        doubleDigit = !doubleDigit;
    }
    return s % 10 == 0;
}
Run Code Online (Sandbox Code Playgroud)

PS不要使用正则表达式,因为它是通过链接完成的.但是使用每张卡的文本定义很有用.这里是:

美国运通: - 从34或37开始,长度为15位.

签证: - 从4开始,长度为13或16位.

万事达卡: - 从51到55开始,长度为16位.

发现: - 从6011开始,长度为16位或以5开头,长度为15位.

大来俱乐部: - 从300到305,36或38开始,长度为14位.

JCB: - 从2131或1800开始,长度为15位或以35开头,长度为16位.

我这样做了:

var validateCardNo = function (no) {
    return (no && checkLuhn(no) &&
        no.length == 16 && (no[0] == 4 || no[0] == 5 && no[1] >= 1 && no[1] <= 5 ||
        (no.indexOf("6011") == 0 || no.indexOf("65") == 0)) ||
        no.length == 15 && (no.indexOf("34") == 0 || no.indexOf("37") == 0) ||
        no.length == 13 && no[0] == 4)
}
Run Code Online (Sandbox Code Playgroud)


NJI*_*dar 7

Luhn的算法用于添加信用卡和借记卡号码的验证.这个Javascript函数应该可行.

function validate_creditcardnumber(inputNum) {
    var digit, digits, flag, sum, _i, _len;
    flag = true;
    sum = 0;
    digits = (inputNum + '').split('').reverse();
    for (_i = 0, _len = digits.length; _i < _len; _i++) {
      digit = digits[_i];
      digit = parseInt(digit, 10);
      if ((flag = !flag)) {
        digit *= 2;
      }
      if (digit > 9) {
        digit -= 9;
      }
      sum += digit;
    }
    return sum % 10 === 0;
  };
Run Code Online (Sandbox Code Playgroud)


Céd*_*vin 7

用这个:

function AmexCardnumber(inputtxt) {
  var cardno = /^(?:3[47][0-9]{13})$/;
  return cardno.test(inputtxt);
}

function VisaCardnumber(inputtxt) {
  var cardno = /^(?:4[0-9]{12}(?:[0-9]{3})?)$/;
  return cardno.test(inputtxt);
}

function MasterCardnumber(inputtxt) {
  var cardno = /^(?:5[1-5][0-9]{14})$/;
  return cardno.test(inputtxt);
}

function DiscoverCardnumber(inputtxt) {
  var cardno = /^(?:6(?:011|5[0-9][0-9])[0-9]{12})$/;
  return cardno.test(inputtxt);
}

function DinerClubCardnumber(inputtxt) {
  var cardno = /^(?:3(?:0[0-5]|[68][0-9])[0-9]{11})$/;
  return cardno.test(inputtxt);
}

function JCBCardnumber(inputtxt) {
  var cardno = /^(?:(?:2131|1800|35\d{3})\d{11})$/;
  return cardno.test(inputtxt);
}

function IsValidCreditCardNumber(cardNumber) {

  var cardType = null;
  if (VisaCardnumber(cardNumber)) {
    cardType = "visa";
  } else if (MasterCardnumber(cardNumber)) {
    cardType = "mastercard";
  } else if (AmexCardnumber(cardNumber)) {
    cardType = "americanexpress";
  } else if (DiscoverCardnumber(cardNumber)) {
    cardType = "discover";
  } else if (DinerClubCardnumber(cardNumber)) {
    cardType = "dinerclub";
  } else if (JCBCardnumber(cardNumber)) {
    cardType = "jcb";
  }

  return cardType;
}
Run Code Online (Sandbox Code Playgroud)