Disable zero as first letter in <input>

前端 未结 7 1323
無奈伤痛
無奈伤痛 2021-02-08 19:51

Below code disables 0 as the first character in #foo.
However, you can bypass this by typing 123, then drag to select 123

7条回答
  •  离开以前
    2021-02-08 20:05

    Accept only numeric values not prefixed by zero. Supports Ctrl + A:

    var escapeKeys = [8, 46];
    $('input#foo').keyup(function (e) {
        if ($.inArray(e.keyCode, escapeKeys) != 0) {
            if ((this.value + String.fromCharCode(e.keyCode)).match(/^[1-9][0-9]*$|^$/) != null) {
                this.lastValidValue = this.value + String.fromCharCode(e.keyCode);
            } else if (this.lastValidValue) {
                this.value = this.lastValidValue;
            } else {
                this.value = "";
            }
        } else {
            this.lastValidValue = this.value;
        }
    });
    
    

提交回复
热议问题