Use value and onChange property of input field to allow only numbers in textbox.
Inside the onChange handle check whether the entered value is valid number or not. Update the state only when entered value is a valid number.
See the below example to do this.
Example 1,
You can use Number and conditionally change state.
import React, { Component } from 'react'; class AllowOnlyNumber extends Component { constructor(props) { super(props); this.state = { telephone: '' }; this.onHandleTelephoneChange = this.onHandleTelephoneChange.bind(this); } onHandleTelephoneChange = e => { let telephone = e.target.value; if (!Number(telephone)) { return; } this.setState({ [e.target.name]: telephone }); }; render() { return ( < > < label > Allow only numbers in Input(React): < / label > < input type = "tel" name = "telephone" placeholder = "Telephone Number" value = { this.state.telephone } onChange = { this.onHandleTelephoneChange } / > < /> ); } }
Example 2,
You can use regex and conditionally change state.
import React, { Component } from 'react'; class AllowOnlyNumber extends Component { constructor(props) { super(props); this.onHandleTelephoneChange = this.onHandleTelephoneChange.bind(this); this.state = { telephone: '', regexp : /^[0-9\b]+$/ } } onHandleTelephoneChange = e => { let telephone = e.target.value; // if value is not blank, then test the regex if (telephone === '' || this.state.regexp.test(telephone)) { this.setState({ [e.target.name]: telephone }) } }; render() { return ( <> < label >Allow only numbers in Input (React) : </ label > < input type="tel" name="telephone" placeholder="Telephone Number" value={this.state.telephone} onChange={this.onHandleTelephoneChange} / > </> ); } } export default AllowOnlyNumber;
Top comments (2)
Hi Anil,
Could you format/highlight code snippets in this article, as well by referring to the Editor Guide?
Actually, I am new here. wen I get time i will try to do the same.