How to allow only numbers in textbox
in reactjs
using regular expression
only?
The simplest and far from complicated way according to www.w3schools.com :
onHandleChangeNumeric = e => {
let valu = e.target.value;
if (!Number(valu)) {
return;
}
this.setState({ [e.target.name]: valu });
};
On render input :
<input
type="text"
className="form-control"
name="someName"
value={this.state.someName}
onChange={this.onHandleChangeNumeric}
/>
Important : Do not make type="number", it won't work.
A simple solution, using hooks:
const [age, setAge] = useState();
const handleChange = (e) => {
const value = e.target.value.replace(/\D/g, "");
setAge(value);
};
return (
<div>
<input value={age} onChange={handleChange} />
</div>
);
Example: https://codesandbox.io/s/adoring-minsky-9sqvv
Even though you said regular expression only this is high up in Google without specifying regular expression (as that's not stated in the title) so I thought I'd add another simple way, not using regular expressions. And given the test results linked below it'd seem silly to use regular expressions for simple use cases.
I found this on another post that I can no longer find. I believe it was referred to as the self-equals check... Not entirely sure how it works. But it's at least 20 times faster than Regex in Chrome (from the test results).
isNumeric(number) {
if (+number === +number) { // if is a number
return true;
}
return false;
}
Benchmarking self-equals vs regex vs NaN
There are revisions to this test at the bottom of the page, number 5 is the one that corresponds to the post I found that had this simple solution, I'm unsure how the other revisions differ.
I use it for my positive number only textboxes like this:
isValidQuantityInput() {
const value = +this.state.quantityInputText; // convert to number
if (value !== +value || value < 0) { // if fails validity check
return false;
}
return true;
}
I don't bind the value of the input to the data as that causes weird usability issues such as not being able to clear the field without highlighting etc... quantityInputText
holds the input text, then I validate it and if it is valid I set my data to it's value.
Basic idea is:
Use controlled component (use value and onChange property of input field), and inside onChange handle check whether the entered value is proper number or not. Update the state only when entered value is a valid number.
For that use this regex: /^[0-9\b]+$/;
onChange handler will be:
onChange(e){
const re = /^[0-9\b]+$/;
// if value is not blank, then test the regex
if (e.target.value === '' || re.test(e.target.value)) {
this.setState({value: e.target.value})
}
}
Working example:
class App extends React.Component{
constructor(){
super();
this.state = {value: ''};
this.onChange = this.onChange.bind(this)
}
onChange(e){
const re = /^[0-9\b]+$/;
if (e.target.value === '' || re.test(e.target.value)) {
this.setState({value: e.target.value})
}
}
render(){
return <input value={this.state.value} onChange={this.onChange}/>
}
}
ReactDOM.render(<App/>,document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='app'/>
The answer provided by Mayank Shukla is correct, no doubt about it.
type="number"
.
No need to use regex in this case as <input type="number" value={this.state.value} onChange={this.onChange}/>
will accept only numbers.
I know you've asked for regular expression.
But here is a solution without regex if anyone wants.
const handlePincode = (e) => {
!isNaN(e.nativeEvent?.data) && setPincode(e.currentTarget.value);
};
return (
<div className="App">
<input type="text" value={pincode} onChange={handlePincode} />
</div>
);
The event.nativeEvent.data
gives me the currently typed value, I can just validate that and set the event.currentTarget.value
or just return it.