javascript中的信用卡验证

时间:2015-12-01 04:28:07

标签: javascript html

我写了这段代码来验证信用卡数字,将其保存为html文件。它不起作用。

<html>
    <head>
        <script>
    function mod10_check(val){
        var nondigits = new RegExp(/[^0-9]+/g);
        var number = val.replace(nondigits,'');
        var pos, digit, i, sub_total, sum = 0;
        var strlen = number.length;
        if(strlen < 13){ return false; }
        for(i=0;i
            <strlen;i++){
            pos = strlen - i;
            digit = parseInt(number.substring(pos - 1, pos));
            if(i % 2 == 1){
                sub_total = digit * 2;
                if(sub_total > 9){
                    sub_total = 1 + (sub_total - 10);
                }
            } else {
                sub_total = digit;
            }
            sum += sub_total;
        }
        if(sum > 0 && sum % 10 == 0){
            return true;
        }
        return false;
    }

            </script>
        </head>
        <body>
            <form>
                <input type="text" 
        name="cc_number" 
        onblur="if(mod10_check(this.value)){$('#cc_error').hide(); }     else     {       $('#cc_error').show(); }" 
        value="" />
                <span id="cc_er`enter code here`ror" style="display:none;">The card   number     is invalid.</span>
            </form>
        </body>
    </html>

不验证在文本框中输入的值。当文本框失焦时,消息未显示。不愿意使用任何第三方插件。这段代码出了什么问题?

1 个答案:

答案 0 :(得分:0)

尝试将内联代码重写为事件处理程序。

&#13;
&#13;
var ccInp = document.getElementById('cc_no');

ccInp.addEventListener('blur', function() {
    if(!mod10_check(ccInp.value)) {       
        document.getElementById('cc_error').style.display = '';       
    }
});

function mod10_check(val){
        var nondigits = new RegExp(/[^0-9]+/g);
        var number = val.replace(nondigits,'');
        var pos, digit, i, sub_total, sum = 0;
        var strlen = number.length;
        if(strlen < 13){ return false; }
        for(i=0;i
            <strlen;i++){
            pos = strlen - i;
            digit = parseInt(number.substring(pos - 1, pos));
            if(i % 2 == 1){
                sub_total = digit * 2;
                if(sub_total > 9){
                    sub_total = 1 + (sub_total - 10);
                }
            } else {
                sub_total = digit;
            }
            sum += sub_total;
        }
        if(sum > 0 && sum % 10 == 0){
            return true;
        }
        return false;
    }
&#13;
<form>
    <input type="text" 
           name="cc_number"            
           value=""
           id="cc_no"/>
    <span id="cc_error" style="display:none;">The card number is invalid.</span>
</form>
&#13;
&#13;
&#13;

jsFiddle:http://jsfiddle.net/8kyhtny2/