How to block +,- and e in Number Input

Have you ever used number input and added special logic on onChange event to prevent +, – and e charterers saving to state. In this article we will gonna learn how to write a util function to block these +, – and e in your number input.

Problem

Let’s see below example.

import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const [value, setValue] = useState("");
  return (
    <div className="App">
      <input
        type="Number"
        value={value}
        onChange={({ target: { value } }) => {
          setValue(value);
        }}
      />
    </div>
  );
}

If you notice we are using a number input and it’s also working fine but we don’t want user to enter +, – and e while typing.

How to block +,- and e in Number Input

Solution

The solution is very straight forward. We will gonna write a reusable util function which basically gonna block invalid characters.

export const blockInvalidChar = e => ['e', 'E', '+', '-'].includes(e.key) && e.preventDefault();

We can simply import this function and use it on onKeyPress event.

import React, { useState } from "react";

import { blockInvalidChar } from "./blockInvalidChar";
import "./styles.css";

export default function App() {
  const [value, setValue] = useState("");
  return (
    <div className="App">
      <input
        type="Number"
        value={value}
        onKeyDown={blockInvalidChar}
        onChange={({ target: { value } }) => {
          setValue(value);
        }}
      />
    </div>
  );
}
How to block +,- and e in Number Input
Edit k63s4

How to use Formik with yup in React


3 Comments

Ivan · June 19, 2020 at 9:01 am

Good solution but it will prevent the user from insert negative numbers like -3000.
To solve this scenario we can check on the onkeypressed event if the value has already number and only in that case stop the user.

Test cases:
-3000 YES
12-30000 NO

    Narender Saini · June 19, 2020 at 9:49 am

    Thanks, But as the title says +,- and e. To allow – we can simply remove – from regex.

DayJS a new alternative to MomentJS - Blog React · June 25, 2020 at 3:27 am

[…] How to block +,- and e in Number Input […]

Comments are closed.