[英]Validate credit card by using jquery
How can i validate credit/debit card by using jquery/javascript? 如何使用jquery / javascript验证信用卡/借记卡?
I have tried to do by using Luhn algorithm. 我试图通过使用Luhn算法来做。
function checkLuhn(input) { var sum = 0; var numdigits = input.length; var parity = numdigits % 2; for(var i=0; i < numdigits; i++) { var digit = parseInt(input.charAt(i)) if(i % 2 == parity) digit *= 2; if(digit > 9) digit -= 9; sum += digit; } return (sum % 10) == 0; }
Do you have any good/simpler way to do it? 您有什么好/简单的方法吗?
Thanks in advance 提前致谢
You can prevent user typing incorrect value in the first place using jQuery Mask Plugin 您可以防止用户使用jQuery Mask Plugin首先输入不正确的值
$('#debit').mask('0000 0000 0000 0000');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="http://igorescobar.github.io/jQuery-Mask-Plugin/js/jquery.mask.min.js"></script> <input type="text" id="debit">
This is how I did it with Luhn-algorithm and card number length (we only support specific cards that have 16 digits): 这就是我用Luhn算法和卡号长度(我们仅支持具有16位数字的特定卡)进行的操作:
// Luhn-algorithm check
function checkCardNumber(number) {
var sumTable = [
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 2, 4, 6, 8, 1, 3, 5, 7, 9]
],
sum = 0,
flip = 0,
i;
for (i = number.length - 1; i >= 0; i--) {
sum += sumTable[flip++ & 0x1][parseInt(number.charAt(i), 10)];
}
return sum % 10 === 0;
}
// Check if the VISA card input is valid
var regCardNo = (opts.cardData ? /^[0-9]{6}[\*]{6}[0-9]{4}$/ : /^[0-9]{16}$/),
regMonth = /^[0]{1}[1-9]{1}$|^[1]{1}[0-2]{1}$/,
regYear = /^[0]{1}[1-9]{1}$|^[1-9]{1}[0-9]{1}$/,
regCvc = /^[0-9]{3}$/,
cardNo = cardNumberInput.val(),
month = monthInput.val(),
year = yearInput.val(),
cvc = cvcInput.val();
if(regCardNo.test(cardNo) && regMonth.test(month) && regYear.test(year) && regCvc.test(cvc) && checkCardNumber(cardNo)) {
payButton.prop("disabled", false);
return true;
} else {
payButton.prop("disabled", true);
return false;
}
All input variables are jQuery elems (they are not defined in this code snippet ) 所有输入变量都是jQuery elems(在此代码段中未定义)
NOTE that the opts.cardData checks if you have a prefilled card number (which gets loaded from the DB), then it checks for a masked number (ex. 123456******1234), else it checks for a full length number which you add in the form your self. 请注意,opts.cardData会检查您是否有预填的卡号(从数据库中加载),然后检查被屏蔽的号码(例如123456 ****** 1234),否则会检查全长您以自己的形式添加的数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.