Reactjs - How To Allow User To Type Only Integers
I'm trying to make if else statement to allow user to type only integer in TextArea but i have no idea how. This is my code: class App extends React.Component { constructor(props
Solution 1:
You can use regex and conditionally change state.
onChange(event){
const regex = /^[0-9\b]+$/;
const value = event.target.value;
if (value === '' || regex.test(value)) {
this.setState({ value })
}
}
Solution 2:
Consider making use of the ValidatorJS Library as opposed to rolling your own validation method.
Example usage in your code would be something like this...
handleChangeCurrencyValue(event) {
console.log('qwer ' + this)
const currencyValue = event.target.value;
if(validator.isInt(currencyValue)) {
this.setState({ currencyValue });
}
}
I recommend using libraries that have been thoroughly tested for validation as this will reduce security concerns down the line. Also, validator
is extremely easy to implement.
Solution 3:
can it be something like that:
<input type="number" min="0" step="1"/>
Solution 4:
You can use regex (regular expression) to handle that. The regex that you use is /[0-9]+/g
.
For example you have input:
<input value={this.state.value} onChange={this.onChange}/>
And the onChange:
onChange(text) {
let newText = '';
const numbers = '^[0-9]';
for (let i = 0; i < text.length; i++) {
if (numbers.indexOf(text[i] > -1)) {
newText += text[i];
}
this.setState({ currencyValue: newText });
}
}
or like this:
onChange(e){
const re = /^[0-9\b]+$/;
if (e.target.value == '' || re.test(e.target.value)) {
this.setState({currencyValue: e.target.value})
}
}
May it can help you! :)
Post a Comment for "Reactjs - How To Allow User To Type Only Integers"