Javascript验证Visa和MasterCard信用卡号的方法
本文实例讲述了Javascript验证Visa和MasterCard信用卡号的方法。分享给大家供大家参考。具体实现方法如下:
visa验证:
<HTML> <head> <title>VisaExample</title> <scripttype="text/javascript"> functionluhnCheckSum(sCardNum){ variOddSum=0; variEvenSum=0; varbIsOdd=true; for(vari=sCardNum.length-1;i>=0;i--){ variNum=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); } functionisValidVisa(sText){ varreVisa=/^(4\d{12}(?:\d{3})?)$/; if(reVisa.test(sText)){ returnluhnCheckSum(RegExp.$1); }else{ returnfalse; } } functionvalidate(){ varoInput1=document.getElementById("txt1"); if(isValidVisa(oInput1.value)){ alert("Valid"); }else{ alert("Invalid!"); } } </script> </head> <body> <P>VisaNumber:<inputtype="text"id="txt1"/><br/> <inputtype="button"value="Validate"onclick="validate()"/></p> </body> </html>
MasterCard验证:
<html> <head> <title>MasterCardExample</title> <scripttype="text/javascript"> functionluhnCheckSum(sCardNum){ variOddSum=0; variEvenSum=0; varbIsOdd=true; for(vari=sCardNum.length-1;i>=0;i--){ variNum=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); } functionisValidMasterCard(sText){ varreMasterCard=/^(5[1-5]\d{2})[\s\-]?(\d{4})[\s\-]?(\d{4})[\s\-]?(\d{4})$/; if(reMasterCard.test(sText)){ varsCardNum=RegExp.$1+RegExp.$2+RegExp.$3+RegExp.$4; returnluhnCheckSum(sCardNum); }else{ returnfalse; } } functionvalidate(){ varoInput1=document.getElementById("txt1"); if(isValidMasterCard(oInput1.value)){ alert("Valid"); }else{ alert("Invalid!"); } } </script> </head> <body> <P>MasterCardNumber:<inputtype="text"id="txt1"/><br/> <inputtype="button"value="Validate"onclick="validate()"/></p> </body> </html>
希望本文所述对大家的javascript程序设计有所帮助。