An Interest In:
Web News this Week
- April 25, 2024
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
- April 19, 2024
June 20, 2020 03:37 am GMT
Original Link: https://dev.to/narendersaini32/how-to-block-and-e-in-number-input-1hoe
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
Lets 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 its also working fine but we dont want user to enter +, and e while typing.
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> );}
Original Link: https://dev.to/narendersaini32/how-to-block-and-e-in-number-input-1hoe
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To