Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
292 views
in Technique[技术] by (71.8m points)

javascript - Format credit card number

How to format and validate a credit card number with spaces between each 4 digit while typing:

eg: 4464 6846 4354 3564

I have tried:

$('.creditno').keyup(function() {
    cc = $(this).val().split("-").join("");

    cc = cc.match(new RegExp('.{1,4}$|.{1,4}', 'g')).join("-");

    $(this).val(cc);

});

Please help

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this:

function cc_format(value) {
    var v = value.replace(/s+/g, '').replace(/[^0-9]/gi, '')
    var matches = v.match(/d{4,16}/g);
    var match = matches && matches[0] || ''
    var parts = []

    for (i=0, len=match.length; i<len; i+=4) {
        parts.push(match.substring(i, i+4))
    }

    if (parts.length) {
        return parts.join(' ')
    } else {
        return value
    }
}

Note: Check this for detailed information https://www.peterbe.com/plog/cc-formatter.

To restrict the user to enter number only:

Javascript Way

<input type="text" id="txt_cardNumber" name="txt_cardNumber" onkeypress="return checkDigit(event)">

function checkDigit(event) {
    var code = (event.which) ? event.which : event.keyCode;

    if ((code < 48 || code > 57) && (code > 31)) {
        return false;
    }

    return true;
}

OR

function checkDigit() {
    var allowedChars = "0123456789";
    var entryVal = document.getElementById('txt_cardNumber').value();
    var flag;

    for(var i=0; i<entryVal.length; i++){       
        flag = false;

        for(var j=0; j<allowedChars.length; j++){
            if(entryVal.charAt(i) == allowedChars.charAt(j)) {
                flag = true; 
            }
        }

        if(flag == false) { 
            entryVal = entryVal.replace(entryVal.charAt(i),""); i--; 
        }
    }

    return true;
}

HTML5 Way

<input type="text" id="txt_cardNumber" name="txt_cardNumber" pattern="[0-9.]+">
<input type="number" id="txt_cardNumber" name="txt_cardNumber">

jQuery Way

$("#txt_cardNumber").keypress(function (e) {
    if ((e.which < 48 || e.which > 57) && (e.which !== 8) && (e.which !== 0)) {
        return false;
    }

    return true;
});

Note: Please check here to get more information about various key code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...