Loading, please wait...

A to Z Full Forms and Acronyms

How to Validate the forms in React

Jul 27, 2020 React, ReactJS, React Form Validation, 4209 Views
In this article, we'll learn to validate the forms in React

How to Validate the forms in React

Before starting How all these things work. First, we will discuss what is Validation?

Validation is a way to checking if the gave information by the end client is right or not. If it isn't right that it's invalid information, at that point we will confine it and show the fitting blunder messages according to necessity with the goal that the client will carry on to give the right information.

Validation also helps us to fill the proper detail in the form such that it may be login form, signup, Basic information form, etc. It plays an important role in web applications also.

To start implementing it, first, we have to create a project in the react using CLI Tool. You can take a look form the previous article HOW TO CREATE A PROJECT. Once all command runs successfully, you may get the resultant with local host:3000.

Now, open the code editor which so ever you want to use for coding. Let take an example of a Basic Information form for Content Writers in Tutorial Link.

Step 1: Create a file Form.css and add following style to it.

.formDiv {    
padding: 21px;    
border-radius: 5px;    
background-color: #f2f2f2;    
}    

input[type=text], select     
{    
width: 100%;    
padding: 12px 20px;    
margin: 8px 0;    
display: inline-block;    
border: 1px solid #ccc;    
border-radius: 4px;    
box-sizing: border-box;    
}    

input[type=submit] {    
width: 100%;    
background-color: #4CAF50;    
color: white;    
padding: 14px 20px;    
margin: 8px 0;    
border: none;    
border-radius: 4px;    
cursor: pointer;    
}    

input[type=submit]:hover {    
background-color: #45a049;    
}    
.showError{    
border-color: #a94442 !important;    
color: #a94442 !important;    
margin-bottom: 15px;    
}

Step 2: Create another file name Form.js 

import React, { Component } from "react";    
import './Form.css'    
    
class Form extends Component {    
    constructor(props) {    
        super(props);    
        this.state = {    
            Name: '',    
            emailId: '',    
            dob: '',    
            gender: 'select',    
            phoneNumber: '',       
            formErrors: {}    
        };    
    
        this.initialState = this.state;    
    }    
    
    handleFormValidation() {    
        const { Name, emailId, dob, gender, phoneNumber } = this.state;    
        let formErrors = {};    
        let formIsValid = true;    
    
           
        if (!Name) {    
            formIsValid = false;    
            formErrors["NameErr"] = "Name is required.";    
        }    
    
           
        if (!emailId) {    
            formIsValid = false;    
            formErrors["emailIdErr"] = "Email id is required.";    
        }    
        else if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(emailId))) {    
    
            formIsValid = false;    
            formErrors["emailIdErr"] = "Invalid email id.";    
        }    
    
          
        if (!dob) {    
            formIsValid = false;    
            formErrors["dobErr"] = "Date of birth is required.";    
        }    
        else {    
            var pattern = /^(0[1-9]|1[0-9]|2[0-9]|3[0-1])\/(0[1-9]|1[0-2])\/([0-9]{4})$/;    
            if (!pattern.test(dob)) {    
                formIsValid = false;    
                formErrors["dobErr"] = "Invalid date of birth";    
            }    
        }    
    
        //Gender    
        if (gender === '' || gender === "select") {    
            formIsValid = false;    
            formErrors["genderErr"] = "Select gender.";    
        }    
    
         
        if (!phoneNumber) {    
            formIsValid = false;    
            formErrors["phoneNumberErr"] = "Phone number is required.";    
        }    
        else {    
            var mobPattern = /^(?:(?:\\+|0{0,2})91(\s*[\\-]\s*)?|[0]?)?[789]\d{9}$/;    
            if (!mobPattern.test(phoneNumber)) {    
                formIsValid = false;    
                formErrors["phoneNumberErr"] = "Invalid phone number.";    
            }    
        }    
    
          
    }    
    
    handleChange = (e) => {    
        const { name, value } = e.target;    
        this.setState({ [name]: value });    
    }    
    
    handleSubmit = (e) => {    
        e.preventDefault();    
    
        if (this.handleFormValidation()) {    
            alert('You have been successfully registered.')    
            this.setState(this.initialState)    
        }    
    }    
    
    render() {    
    
        const { NameErr, emailIdErr, dobErr, genderErr, phoneNumberErr } = this.state.formErrors;    
    
        return (    
            <div className="formDiv">   
                <h3 style={{ textAlign: "center" }} >Tutorial Link </ h3>
                <h3 style={{ textAlign: "center" }} >Basic Registraion Form </ h3>    
                <div>    
                    <form onSubmit={this.handleSubmit}>    
                        <div>    
                            <label htmlFor="Name">Name</label>    
                            <input type="text" name="Name"    
                                value={this.state.Name}    
                                onChange={this.handleChange}    
                                placeholder="Your name.."    
                                className={NameErr ? ' showError' : ''} />    
                            {NameErr &&    
                                <div style={{ color: "red", paddingBottom: 10 }}>{NameErr}</div>    
                            }    
    
                        </div>    
                        <div>    
                            <label htmlFor="emailId">Email Id</label>    
                            <input type="text" name="emailId"    
                                value={this.state.emailId}    
                                onChange={this.handleChange}    
                                placeholder="Your email id.."    
                                className={emailIdErr ? ' showError' : ''} />    
                            {emailIdErr &&    
                                <div style={{ color: "red", paddingBottom: 10 }}>{emailIdErr}</div>    
                            }    
    
                        </div>    
                        <div>    
                            <label htmlFor="text">Birth Date</label>    
                            <input type="text" name="dob"    
                                value={this.state.dob}    
                                onChange={this.handleChange}    
                                placeholder="DD/MM/YYYY.."    
                                className={dobErr ? ' showError' : ''} />    
                            {dobErr &&    
                                <div style={{ color: "red", paddingBottom: 10 }}>{dobErr}</div>    
                            }    
                        </div>    
                        <div>    
                            <label htmlFor="gender">Gender</label>    
                            <select name="gender" onChange={this.handleChange}    
                                className={genderErr ? ' showError' : ''}    
                                value={this.state.gender} >    
                                <option value="select">--Select--</option>    
                                <option value="male">Male</option>    
                                <option value="female">Female</option>    
                                <option value="female">Other</option>    
                            </select>    
                            {genderErr &&    
                                <div style={{ color: "red", paddingBottom: 10 }}>{genderErr}</div>    
                            }    
                        </div>    
                        <div>    
                            <label htmlFor="phoneNumber">Phone Number</label>    
                            <input type="text" name="phoneNumber"    
                                onChange={this.handleChange}    
                                value={this.state.phoneNumber}    
                                placeholder="Your phone number.."    
                                className={phoneNumberErr ? ' showError' : ''} />    
                            {phoneNumberErr &&    
                                <div style={{ color: "red", paddingBottom: 10 }}>{phoneNumberErr}</div>    
                            }    
                        </div>    
                        <input type="submit" value="Submit" />    
                    </form>  
                      
                </div>    
            </div >    
        )    
    }    
}    
    
export default Form;

Step 3: Import the component Form.js to App.js

import React from 'react';
import './Form.js'
import Form from './Form.js';
class App extends React.Component {

  render() {
    return(
      <div classname="App">
        <h1> Tutorial Link</h1>
       
        
      </div>
    )
  }
}

export default Form; 

Step 4: Now, run the command 

npm start -o

Step 5: Output will show on the browser:

Step 6: If they are valid entry in all the fields then it may not show any warning message and data stored is successful else it shows error.

This is how Form validation works!!

A to Z Full Forms and Acronyms