繁体   English   中英

信用卡号码验证

[英]Credit Card Number Validation

您好,我的 javascript 验证遇到问题。 我正在尝试验证一个信用卡号,我希望它显示在 13 到 18 个数字和单个空格之间。

我的 Javascript 代码:

<script type="text/javascript">
function validateForm()
{
var x=document.forms["checkout_details"]["creditcard"].value;
    if(x.length != 13 || x.length != 18)//if the length is not 13 or 18
    {
        alert("Please enter a valid credit card number");//display message to user;
        return false;
    }    
}
</script>

HTML/PHP 代码:

echo '<form name="checkout_details" action="confirm.php" onsubmit="return validateForm()" method="post">';
echo '<font color="red">*</font>&nbsp;<b>Credit Card Number:</b> <input type="text" name="creditcard" id="creditcard"><br /><br />';
echo '<input type="submit" value="Purchase">';
echo '</form>';

任何人都帮我告诉我我做错了什么。 谢谢。

代替

if(x.length != 13 || x.length != 18)

你应该使用

if(x.length != 13 && x.length != 18)

实际上,在您的原始状态下,18与13会不同,那将返回true

另外,它仅接受13或18的确切长度,如果您想拒绝小于13或大于18的任何内容,则需要

if(x.length < 13 || x.length > 18)

你的意思是

if (x.length < 13 || x.length > 18) {
    ...
}

原件抱怨长度不完全是13 18个字符; 也就是说: 总是 ,因为长度为13的字符串不能为18,反之亦然; 您也想匹配两者之间的所有长度。

信用卡验证不是那么简单。 您应该使用正则表达式进行检查。 也有各种各样的信用卡格式。

您可以在此处查看其他正则表达式信用卡正则表达式

不应该是:

if(x.length < 13 || x.length > 18)

尝试这个

if(x.length > 13 && x.length < 18) //if the length is between 13 and 18

这里还有一个非常好的CC验证插件

jQuery信用卡验证器

验证信用卡不仅仅是卡号的长度。 要正确验证卡号(包括长度),您应该对 Luhn 算法进行检查。 使用此代码:

 const options = { method: 'GET', headers: {Accept: 'application/json', 'X-Api-Key': '[APIkey]'} }; fetch('https://api.epaytools.com/Tools/luhn?number=[CardNumber]&metaData=true', options).then(response => response.json()).then(response => console.log(response)).catch(err => console.error(err));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM