react input only numbers code example
Example 1: react allow only numbers in input
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'))
Example 2: react input number validation
const rx_live = /^[+-]?\d*(?:[.,]\d*)?$/;
class TestForm extends React.Component {
constructor() {
super();
this.state = {
depositedAmount: ''
};
}
handleDepositeAmountChange = (evt) => {
if (rx_live.test(evt.target.value))
this.setState({ depositedAmount : evt.target.value });
}
render() {
return (
<form>
<input
type="text"
id="depositedAmount"
maxLength={9}
pattern="[+-]?\d+(?:[.,]\d+)?"
placeholder="Enter amount"
onChange={this.handleDepositeAmountChange}
value={this.state.depositedAmount}
/>
</form>
)
}
}