How to allow only numbers in textbox in reactjs using regular expression only?
To only allow numbers to be entered in an input in React, we can set the pattern attribute of the input to only allow digits to be inputted. Then in the onChange handler, we only set the value of the input when the inputted value is valid.
By default, HTML 5 input field has attribute type=”number” that is used to get input in numeric format. Now forcing input field type=”text” to accept numeric values only by using Javascript or jQuery. You can also set type=”tel” attribute in the input field that will popup numeric keyboard on mobile devices.
You can use the <input> tag with attribute type='number'. This input field allows only numerical values.
Use the maxLength prop to set a character limit on an input field in React, e.g. <input maxLength={5} /> . The maxLength attribute defines the maximum number of characters the user can enter into an input field or a textarea element.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With