How to block +,-,e in input type Number?

后端 未结 13 1827
我在风中等你
我在风中等你 2020-12-29 20:52

When I\'m giving input type number the letter e and special charecters are also displaying in input field. I want to display only digits. How to block them?

13条回答
  •  北海茫月
    2020-12-29 21:06

    You can block entering those chars with keydown event

    var inputBox = document.getElementById("inputBox");
    
    var invalidChars = [
      "-",
      "+",
      "e",
    ];
    
    inputBox.addEventListener("keydown", function(e) {
      if (invalidChars.includes(e.key)) {
        e.preventDefault();
      }
    });

    but the user can still enter them if s/he does a copy/paste (or through the console). To prevent copy/paste, you can do a replace on the entered value [*].

    var inputBox = document.getElementById("inputBox");
    
    var invalidChars = [
      "-",
      "+",
      "e",
    ];
    
    inputBox.addEventListener("input", function() {
      this.value = this.value.replace(/[e\+\-]/gi, "");
    });
    
    inputBox.addEventListener("keydown", function(e) {
      if (invalidChars.includes(e.key)) {
        e.preventDefault();
      }
    });


    * You can't really get the entered value on an input field with type set to number. You can get the entered value as long as it is a number, that is, the value passes the internal number check. If the user copy/paste 1e, suggested solution will fail.

    What happens when you enter 1e is that, input field checks if it's a number, and if it's not (1e is not) it throws a warning:

    The specified value "1e" is not a valid number. The value must match to the following regular expression: -?(\d+|\d+.\d+|.\d+)([eE][-+]?\d+)?

    and the value property is set to "".

    If you check the field's properties, you'll find valueAsNumber property. If the entered value is a number, input field parses the value and stores it in valueAsNumber. Since 1e is not a number, it evaluates to NaN, and NaN is assigned to valueAsNumber and value is set to "". Though you still see 1e on the input field.

    I've asked a question related to this problem, but no solution yet.

    Get the entered value on number input field, not the parsed

提交回复
热议问题