Format credit card number

后端 未结 10 2210
梦谈多话
梦谈多话 2020-12-08 11:27

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:

10条回答
  •  借酒劲吻你
    2020-12-08 12:05

    I couldn't find a reasonable solution that works with text editing, so here you go:

    $("#cardNumber").on("keydown", function(e) {
        var cursor = this.selectionStart;
        if (this.selectionEnd != cursor) return;
        if (e.which == 46) {
            if (this.value[cursor] == " ") this.selectionStart++;
        } else if (e.which == 8) {
            if (cursor && this.value[cursor - 1] == " ") this.selectionEnd--;
        }
    }).on("input", function() {
        var value = this.value;
        var cursor = this.selectionStart;
        var matches = value.substring(0, cursor).match(/[^0-9]/g);
        if (matches) cursor -= matches.length;
        value = value.replace(/[^0-9]/g, "").substring(0, 16);
        var formatted = "";
        for (var i=0, n=value.length; i

    The keydown listener is needed to adjust the cursor position for backspace and delete to move past spaces. It should not be used to restrict character entry, as you don't want to use key codes for that.

    The input listener rebuilds the text, strips non-numbers, adds spaces every 4 characters, and preserves the cursor position.

提交回复
热议问题