React JS Form Validation Example Tutorial

Sep 20, 2022 . Admin

Hey Guys,

This tutorial is focused on react js form validation example. This article will give you a simple example of form validation in react js. We will use form validation in react js functional component. let’s discuss about how to add form validation in react js. So, let's follow a few steps to create an example of how to put validation in react js form.

In this example, we will create simple user form with name, email and comment. Then we will add form validation for name, email and comment input. so let's see below example code.

Step 1: Create React JS App

In this step, open your terminal and execute the following command on your terminal to create a new react app:

npx create-react-app react-axios-example
Step 2: Install Bootstrap

In this step, we will install bootstrap npm package to use design css. let's run below command:

npm install bootstrap --save
Step 3: Create UserForm.js Component

Here, we will create UserForm.js component and make form. Then we will add form validation on it. so let's update code on following file.

src/UserForm.js
import React, { Component } from "react";

export default class UserForm extends Component {

    constructor() {
    super();
    this.state = {
      input: {},
      errors: {}
    };
     
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }
     
  handleChange(event) {
    let input = this.state.input;
    input[event.target.name] = event.target.value;
  
    this.setState({
      input
    });
  }
    
  handleSubmit(event) {
    event.preventDefault();
  
    if(this.validate()){
        console.log(this.state);
  
        let input = {};
        input["name"] = "";
        input["email"] = "";
        input["comment"] = "";
        this.setState({input:input});
  
        alert('Demo Form is submited');
    }
  }
  
  validate(){
      let input = this.state.input;
      let errors = {};
      let isValid = true;
  
      if (!input["name"]) {
        isValid = false;
        errors["name"] = "Please enter your name.";
      }
  
      if (!input["email"]) {
        isValid = false;
        errors["email"] = "Please enter your email Address.";
      }
  
      if (typeof input["email"] !== "undefined") {
          
        var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
        if (!pattern.test(input["email"])) {
          isValid = false;
          errors["email"] = "Please enter valid email address.";
        }
      }
  
      if (!input["comment"]) {
        isValid = false;
        errors["comment"] = "Please enter your comment.";
      }
  
      this.setState({
        errors: errors
      });
  
      return isValid;
  }
     
  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
  
          <div className="form-group">
            <label for="name">Name:</label>
            <input 
              type="text" 
              name="name" 
              value={this.state.input.name}
              onChange={this.handleChange}
              className="form-control" 
              placeholder="Enter name" 
              id="name" />
  
              <div className="text-danger">{this.state.errors.name}</div>
          </div>
  
          <div className="form-group">
            <label for="email">Email Address:</label>
            <input 
              type="text" 
              name="email" 
              value={this.state.input.email}
              onChange={this.handleChange}
              className="form-control" 
              placeholder="Enter email" 
              id="email" />
   
              <div className="text-danger">{this.state.errors.email}</div>
          </div>
  
          <div className="form-group">
            <label for="comment">Comment:</label>
            <textarea 
              name="comment"
              value={this.state.input.comment} 
              onChange={this.handleChange}
              placeholder="Enter comment"
              className="form-control" />
  
              <div className="text-danger">{this.state.errors.comment}</div>
          </div>
             
          <input type="submit" value="Submit" className="btn btn-success" />
        </form>
      </div>
    );
  }
}
Step 4: Update App.js File

Here, we will update our App.js file code. we will import UserForm component and import bootstrap for design. so let's update code on App.js file.

src/App.js
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import UserForm from './UserForm';

function App() {

  return (
    <div className="container">
        <h1>React JS Form Validation Example - MyWebtuts.com</h1>
        <UserForm />
    </div>
  );
}

export default App;
Step 5: Run React JS App

In the last step run your project using bellow command.

npm start
Output

I hope it can help you...

#React JS