How to allow only numbers in textbox in reactjs?

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


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.


But instead of it, you can just use the default html property 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.

Tags:

Reactjs