DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> Javascript驗證Visa和MasterCard信用卡號的方法
Javascript驗證Visa和MasterCard信用卡號的方法
編輯:關於JavaScript     

本文實例講述了Javascript驗證Visa和MasterCard信用卡號的方法。分享給大家供大家參考。具體實現方法如下:

visa驗證:

<HTML>
 <head>
  <title>Visa Example</title>
  <script type="text/javascript">
    function luhnCheckSum(sCardNum) {
     var iOddSum = 0;
     var iEvenSum = 0;
     var bIsOdd = true;
     for (var i=sCardNum.length-1; i >= 0; i--) {
      var iNum = parseInt(sCardNum.charAt(i));
      if (bIsOdd) {
       iOddSum += iNum;
      } else {
       iNum = iNum * 2;
       if (iNum > 9) {
        iNum = eval(iNum.toString().split("").join("+"));
       }
       iEvenSum += iNum;
      }
      bIsOdd = !bIsOdd;
     }
     return ((iEvenSum + iOddSum) % 10 == 0);
    }
    function isValidVisa(sText) {
     var reVisa = /^(4\d{12}(?:\d{3})?)$/;
     if (reVisa.test(sText)) {
      return luhnCheckSum(RegExp.$1);
     } else {
      return false;
     }
    }
    function validate() {
     var oInput1 = document.getElementById("txt1");
     if (isValidVisa(oInput1.value)) {
      alert("Valid");
     } else {
      alert("Invalid!");
     }
    }
  </script>
 </head>
 <body>
  <P>Visa Number: <input type="text" id="txt1" /><br />
  <input type="button" value="Validate" onclick="validate()" /></p>
 </body>
</html>

MasterCard驗證:

<html>
 <head>
  <title>MasterCard Example</title>
  <script type="text/javascript">
    function luhnCheckSum(sCardNum) {
     var iOddSum = 0;
     var iEvenSum = 0;
     var bIsOdd = true;
     for (var i=sCardNum.length-1; i >= 0; i--) {
      var iNum = parseInt(sCardNum.charAt(i));
      if (bIsOdd) {
       iOddSum += iNum;
      } else {
       iNum = iNum * 2;
       if (iNum > 9) {
        iNum = eval(iNum.toString().split("").join("+"));
       }
       iEvenSum += iNum;
      }
      bIsOdd = !bIsOdd;
     }
     return ((iEvenSum + iOddSum) % 10 == 0);
    }
    function isValidMasterCard(sText) {
     var reMasterCard = /^(5[1-5]\d{2})[\s\-]?(\d{4})[\s\-]?(\d{4})[\s\-]?(\d{4})$/;
     if (reMasterCard.test(sText)) {
      var sCardNum = RegExp.$1 + RegExp.$2 + RegExp.$3 + RegExp.$4;
      return luhnCheckSum(sCardNum);
     } else {
      return false;
     }
    }
    function validate() {
     var oInput1 = document.getElementById("txt1");
     if (isValidMasterCard(oInput1.value)) {
      alert("Valid");
     } else {
      alert("Invalid!");
     }
    }
  </script>
 </head>
 <body>
  <P>MasterCard Number: <input type="text" id="txt1" /><br />
  <input type="button" value="Validate" onclick="validate()" /></p>
 </body>
</html>

希望本文所述對大家的javascript程序設計有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved