45fan.com - 路饭网

搜索: 您的位置主页 > 电脑频道 > 编程代码 > 阅读资讯:Javascript如何验证Visa和MasterCard的信用卡号?

Javascript如何验证Visa和MasterCard的信用卡号?

2015-08-13 15:05:46 来源:www.45fan.com 【

Javascript如何验证Visa和MasterCard的信用卡号?

本文实例讲述了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程序设计有所帮助。


本文地址:http://www.45fan.com/bcdm/17648.html
Tags: 验证 JavaScript Visa
编辑:路饭网
推广内容
推荐阅读
热门推荐
推荐文章
关于我们 | 联系我们 | 友情链接 | 网站地图 | Sitemap | App | 返回顶部