How to allow only numbers in input field React?
May 26, 2022Hi Friends 👋,
Welcome To aGuideHub! ❤️
To allow only numbers in the input field in react js, you can use the input pattern
attribute with [0-9]*
number regex to the only numeric value in react input.
See a short example of using the pattern
attribute with [0-9]*
number regex to restrict the user to enter only digits.
<input
type="number"
pattern="[0-9]*"
value={val}
onChange={(e) =>
setVal((v) => (e.target.validity.valid ? e.target.value : v))
}
/>
Today, I am going to show you. two ways to allow a user to enter numbers only in react input field.
- Input field allows only numbers using the pattern attribute
- Input field allows only numbers using regex in the onChange function
Let’s start today’s tutorial only accept numbers in input react
Input field allows only numbers using the pattern
attribute
In this example, I will do the following things to only allow numbers in input to react using a pattern.
- Create a state with empty state value
useState("")
. - Put
[0-9]*
regex in react input pattern attribute - Validate value in
onChange
attribute before setting value in the state
App.js
import React, { useState } from "react";
export default function App() {
const [val, setVal] = useState("");
return (
<div>
<input
type="number"
pattern="[0-9]*"
value={val}
onChange={(e) =>
setVal((v) => (e.target.validity.valid ? e.target.value : v))
}
/>
</div>
);
}
Here, we are provided code sandbox links for the above program for the example react allows only numbers in input. Then you can use it whenever you want and do the changes as per your requirements.
Input field allow only numbers using regex in onChange function
In this example, I will do the following things to only allow numbers in input to react using regex in the onchange function.
- Create a state with empty state value
useState("")
. - Create a
handleChange
function and validate value is a number or not before storing it in the state. - Call the
handleChange
function from react inputonChange
attribute.
App.js
import React, { useState } from "react";
export default function App() {
const [val, setVal] = useState("");
const handleChange = (e) => {
const regex = /^[0-9\b]+$/;
if (e.target.value === "" || regex.test(e.target.value)) {
setVal(e.target.value);
}
};
return (
<div>
<input
placeholder="Age"
type="number"
value={val}
onChange={handleChange}
/>
</div>
);
}
Here, we are provided code sandbox links for the above program for the example react input only number using regex. Then you can use it whenever you want and do the changes as per your requirements.
All the best 👍