Categories
React Answers

How to Only Allow Numbers to be Inputted in React?

Spread the love

Sometimes, we want to only allow numbers to be inputted in an input box in a React component.

In this article, we’ll look at how to only allow numbers to be inputted in an input box in a React component.

Only Allow Numbers to be Inputted in React

We can set the pattern attribute to the regex string we want for restricting the input to numbers.

For instance, we can write:

<input type="text" pattern="[0-9]*" onInput={this.handleChange.bind(this)} value={this.state.goal} />

We specified the pattern and we listen to the inpurt pro.

Then in the handleChange method, we can write:

handleChange(evt) {
  const goal = (evt.target.validity.valid) ?
  evt.target.value : this.state.goal;
  this.setState({ goal });
}

We only set the state if it’s valid, then we won’t get any invalid input in the state.

Conclusion

We can set the pattern attribute to the regex string we want for restricting the input to numbers.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.