简体   繁体   中英

Credit card validation in javascript

I wrote this code to validate credit card digits, saved it as an html file. It's not working though.

<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>

Does not validate value entered in the textbox. When the textbox goes out of focus message is not shown.Not willing to use any third party plugin.What is wrong with this code?

Try re-writing your inline code as an event handler.

 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; } 
 <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> 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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