loading...

How to block +,- and e in Number Input

narendersaini32 profile image Narender Saini ・2 min read

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

Posted on Jun 20 by:

narendersaini32 profile

Narender Saini

@narendersaini32

I am Senior Reactjs developer with 4 year of experience. Apart from freelancing work I am a mentor teaching 100's of students around the globe. I love to share knowledge regarding Reactjs.

Discussion

markdown guide
 

I used to cast value to number explicitly using Number(e.target.value).

 

I'm not sure if this is a problem in React, but in my experience with vanilla js and the onkeydown event it sometimes misses the last typed character (In some browsers). If you see this poblem just use the onkeyup event instead! :)