{

Reactjs Input number validation


Input form is a basic form to take input from user, Form contains different input control types. We have to do validation to accept valid date only. One of the validation in number on form is 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 form with one input field, Validation errors displayed on change event handler.

onChange - executed whenever input value changed in textbox and onClick event - submitting 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 input box, this will be fire on changing input value
  • In 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 render method, display the validation errors from isValid retrieved from state

Here is 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

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

React has a separate syntax for keypress event called onKeyPress

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

Here is an keypress event binder method,

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

Regular expression is written only accepts numbers, if entered value is not passed with expression, It wont 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 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;
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.