How to Block +,-,E in Input Type Number

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

Try preventing the default behaviour if you don't like the incoming key value:

document.querySelector(".your_class").addEventListener("keypress", function (evt) {    if (evt.which != 8 && evt.which != 0 && evt.which < 48 || evt.which > 57)    {        evt.preventDefault();    }});
// 0 for null values// 8 for backspace // 48-57 for 0-9 numbers
<input type="number" class="your_class">

How do I restrict "+ - e , ." from HTML number input?

Edit: Boris K has got an even better answer.

Original answer:

This would be a way to accomplish that:

var ageInput = document.getElementById("age")

ageInput.addEventListener("keydown", function(e) {
// prevent: "e", "=", ",", "-", "."
if ([69, 187, 188, 189, 190].includes(e.keyCode)) {
e.preventDefault();
}
})
<input type="number" id="age">

Why does the html input with type "number" allow the letter 'e' to be entered in the field?

Because that's exactly how the spec says it should work. The number input can accept floating-point numbers, including negative symbols and the e or E character (where the exponent is the number after the e or E):

A floating-point number consists of the following parts, in exactly
the following order:

  1. Optionally, the first character may be a "-" character.
  2. One or more characters in the range "0—9".
  3. Optionally, the following parts, in exactly the following order:

    1. a "." character
    2. one or more characters in the range "0—9"
  4. Optionally, the following parts, in exactly the following order:

    1. a "e" character or "E" character
    2. optionally, a "-" character or "+" character
    3. One or more characters in the range "0—9".

Disable writing in input type number HTML5

If you are able/allowed to use jQuery, you can disable keypress on the type='number'.

$("[type='number']").keypress(function (evt) {
evt.preventDefault();
});

This allows you to use up and down arrows on the input, but doesn't allow keyboard input.

Is there any way to prevent input type="number" getting negative values?

Use the min attribute like this:

<input type="number" min="0">

How to block typing "e" and "-" characters in React Hook Form input?

If you want to prevent certain keys from being pressed, you can surpress the keydown event after the check is failed:

<Input
onKeyPress={(e) => {
if (e.key === "e" || e.key === "-") {
e.preventDefault();
}
}}
/>

But if you allow all keys but validate it after being pressed, you can use the pattern option like this:

<Controller
name="phone"
control={control}
rules={{ required: true, pattern: /^\d+$/ }}
render={(props) => {
const { onChange, value, ref } = props.field; // v7. use props if you're using v6
const { error } = props.meta;

return (
<Input
ref={ref}
type="number"
label="phone"
onChange={onChange}
val={value}
/>
);
}}
/>


Related Topics



Leave a reply



Submit