Reactjs Input number validation with example

The input form is a basic form to take input from the user, Form contains different input control types. We have to validate to accept valid dates only. One of the validations in numbers on the form is a simple thing to do.

In this tutorial, We are going to learn multiple ways to learn input number validation in React application. Other versions available:

React offer multiple ways to do form handling

Display errors with input number validation

In this example, We have a form with one input field, Validation errors displayed on the change event handler.

onChange - executed whenever input value changes in the textbox and onClick event - submitting the form once it is valid.

Let’s create a react component.

  • Declare input form variable in the state with default values
  • isValid value default to true to handle error cases
  • onChange handler is attached to an input box, this will be fire on changing the input value
  • In the event handler, Testing entered value against regular expression for numbers, if it is not valid update state with isValid: false and entered value to new value.
  • In the render method, display the validation errors from isValid retrieved from the state

Here is the complete react component code :

import React, { Component } from "react";

class InputNumberComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      myNumber: "",
      isValid: true,
    };
  }

  validateNumberField = (myNumber) => {
    const numberRegEx = /\-?\d*\.?\d{1,2}/;
    return numberRegEx.test(String(myNumber).toLowerCase());
  };

  changeUrl = (e) => {
    const { value } = e.target;
    const isValid = !value || this.validateNumberField(value);
    console.log("isValid", isValid);
    this.setState({
      myNumber: value,
      isValid,
    });
  };

  submitForm = () => {
    const { myNumber } = this.state;
    console.log("Number", myNumber);
  };

  render() {
    const { isValid, myNumber } = this.state;
    return (
      <div className="App">
        <form>
          <input
            type="text"
            name="number"
            value={myNumber}
            onChange={this.changeUrl}
          />
          {!isValid && (
            <div style={{ color: "red" }}>Entered Number is invalid</div>
          )}
          <p>
            <button onClick={this.submitForm} disabled={!isValid}>
              Submit
            </button>
          </p>
        </form>
      </div>
    );
  }
}

export default InputNumberComponent;

Output:

React input number regex pattern validation example

Using keypress accepts only numbers

the keypress is a JavaScript native event, that will be fired if any key is entered from the keyboard. So, How do you handle the keypress event in React?

React has a separate syntax for keypress event called onKeyPress

<input type="text" onKeyPress="{this.onKeyPressEvent}" />

Here is a keypress event binder method,

keypress event is directly linked to DOM, any changes in input text refresh the page, So you have to add event.preventDefault() method not to reload the page.

A regular expression is written only accepts numbers, if the entered value is not passed with the expression, It won’t accept data.

onKeyPressEvent = (event) => {
  const keyCode = event.keyCode || event.which;
  const keyValue = String.fromCharCode(keyCode);
  if (!new RegExp("[0-9]").test(keyValue)) event.preventDefault();
  return;
};

Here is the complete react component code:

import React, { Component } from "react";

class InputNumber1 extends Component {
  onKeyPressEvent = (event) => {
    const keyCode = event.keyCode || event.which;
    const keyValue = String.fromCharCode(keyCode);
    if (!new RegExp("[0-9]").test(keyValue)) event.preventDefault();
    return;
  };

  render() {
    return (
      <div>
        <input type="text" onKeyPress={this.onKeyPressEvent} />
      </div>
    );
  }
}

export default InputNumber1;