How to allow only numbers in textbox in reactjs?

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'/>

Leave a Comment