ReactJS Form Validation 😇

In this article, we are going to learn about how to implement form validation in ReactJS with a simple example.

In this article we are going to learn about how to implement form validation in ReactJS with simple example.
 
Description
 
ReactJS is front-end JavaScript library used for building user interface. It is currently the most famous JavaScript library. It is maintained by Facebook and a community of individual developers and companies.
 
Prerequisites
Run following command to create a sample project
  1. npm install -g create-react-app
  2. create-react-app reactjs-validation
  3. cd reactjs-validation
  4. npm start -o
Once the above command runs successfully, you will find an output on the browser like the below screen.
 
Demo screen after created a project 
 
Note :- Screen output for you might be slightly different as per your version of reactjs.
  1. Run the below commands for open project in the Visual Studio Code
    1. Press control + c command, it will ask you a "Terminate batch job (Y/N)?", Press Y to stop the execution
    2. Write “code .” in your project directory and press enter
Command for open project in vs code
 
The above command will open your created project in the Visual Studio Code like below.
 

ReactJS form validation

 
What is validation? - It is the process of checking/ensuring if the provided data by end user is correct or not. If it is not correct or if it's invalid data then we will restrict it and show the appropriate error messages as per field/requirement so that the user will behave to provide the correct/valid data.
 
In our case, we are going to apply this validation to HTML form using ReactJS.
 
Example
 
In this example, we are going to create a Student Admission Form. In this form, we will add Student Name, Email Id, Birth Date, Gender, Phone Number fields to enter data by user. The Screen will look like below.
 
Demo student registration form form 
 
Let’s start
  1. Create two new js files into src folder
    • AdmissionForm.js
    • AdmissionForm.css
  2. Add following style into AdmissionForm.css
    1. .formDiv {    
    2. padding21px;    
    3.  border-radius: 5px;    
    4.  background-color#f2f2f2;    
    5. }    
    6.     
    7. input[type=text], select     
    8. {    
    9.   width100%;    
    10.   padding12px 20px;    
    11.   margin8px 0;    
    12.   display: inline-block;    
    13.   border1px solid #ccc;    
    14.   border-radius: 4px;    
    15.   box-sizing: border-box;    
    16. }    
    17.     
    18. input[type=submit] {    
    19.   width100%;    
    20.   background-color#4CAF50;    
    21.   colorwhite;    
    22.   padding14px 20px;    
    23.   margin8px 0;    
    24.   bordernone;    
    25.   border-radius: 4px;    
    26.   cursorpointer;    
    27. }    
    28.     
    29. input[type=submit]:hover {    
    30.   background-color#45a049;    
    31. }    
    32. .showError{    
    33.   border-color#a94442 !important;    
    34.   color#a94442 !important;    
    35.   margin-bottom15px;    
    36. }
  3. Create a component with name AdmissionForm in AdmissionForm.js and add below code into it
    1. import React, { Component } from "react";    
    2.     
    3. class AdmissionForm extends Component {    
    4.     render() {    
    5.         return (    
    6.             <h1>This Admission Form Component</h1>    
    7.         )    
    8.     }    
    9. }    
    10.     
    11. export default AdmissionForm;
  4. Create a component with name AdmissionForm in AdmissionForm.js and Import AdmissionForm.css file into it.

    In this example, I am going to use
    1. onChange function for binding the input textbox value to state.
    2. className with ternary operator to apply class base on condition.
    3. onSubmit callback function to submit the form data. 
    4. handleFormValidation user defined function to validate input fields.

      Code
      1. import React, { Component } from "react";    
      2. import './AdmissionForm.css'    
      3.     
      4. class AdmissionForm extends Component {    
      5.     constructor(props) {    
      6.         super(props);    
      7.         this.state = {    
      8.             studName: '',    
      9.             emailId: '',    
      10.             dob: '',    
      11.             gender: 'select',    
      12.             phoneNumber: '',    
      13.             city: 'select',    
      14.             formErrors: {}    
      15.         };    
      16.     
      17.         this.initialState = this.state;    
      18.     }    
      19.     
      20.     handleFormValidation() {    
      21.         const { studName, emailId, dob, gender, phoneNumber, city } = this.state;    
      22.         let formErrors = {};    
      23.         let formIsValid = true;    
      24.     
      25.         //Student name     
      26.         if (!studName) {    
      27.             formIsValid = false;    
      28.             formErrors["studNameErr"] = "Name is required.";    
      29.         }    
      30.     
      31.         //Email    
      32.         if (!emailId) {    
      33.             formIsValid = false;    
      34.             formErrors["emailIdErr"] = "Email id is required.";    
      35.         }    
      36.         else if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(emailId))) {    
      37.     
      38.             formIsValid = false;    
      39.             formErrors["emailIdErr"] = "Invalid email id.";    
      40.         }    
      41.     
      42.         //DOB    
      43.         if (!dob) {    
      44.             formIsValid = false;    
      45.             formErrors["dobErr"] = "Date of birth is required.";    
      46.         }    
      47.         else {    
      48.             var pattern = /^(0[1-9]|1[0-9]|2[0-9]|3[0-1])\/(0[1-9]|1[0-2])\/([0-9]{4})$/;    
      49.             if (!pattern.test(dob)) {    
      50.                 formIsValid = false;    
      51.                 formErrors["dobErr"] = "Invalid date of birth";    
      52.             }    
      53.         }    
      54.     
      55.         //Gender    
      56.         if (gender === '' || gender === "select") {    
      57.             formIsValid = false;    
      58.             formErrors["genderErr"] = "Select gender.";    
      59.         }    
      60.     
      61.         //Phone number    
      62.         if (!phoneNumber) {    
      63.             formIsValid = false;    
      64.             formErrors["phoneNumberErr"] = "Phone number is required.";    
      65.         }    
      66.         else {    
      67.             var mobPattern = /^(?:(?:\\+|0{0,2})91(\s*[\\-]\s*)?|[0]?)?[789]\d{9}$/;    
      68.             if (!mobPattern.test(phoneNumber)) {    
      69.                 formIsValid = false;    
      70.                 formErrors["phoneNumberErr"] = "Invalid phone number.";    
      71.             }    
      72.         }    
      73.     
      74.         //City    
      75.         if (city === '' || city === "select") {    
      76.             formIsValid = false;    
      77.             formErrors["cityErr"] = "Select city.";    
      78.         }    
      79.     
      80.         this.setState({ formErrors: formErrors });    
      81.         return formIsValid;    
      82.     }    
      83.     
      84.     handleChange = (e) => {    
      85.         const { name, value } = e.target;    
      86.         this.setState({ [name]: value });    
      87.     }    
      88.     
      89.     handleSubmit = (e) => {    
      90.         e.preventDefault();    
      91.     
      92.         if (this.handleFormValidation()) {    
      93.             alert('You have been successfully registered.')    
      94.             this.setState(this.initialState)    
      95.         }    
      96.     }    
      97.     
      98.     render() {    
      99.     
      100.         const { studNameErr, emailIdErr, dobErr, genderErr, phoneNumberErr, cityErr } = this.state.formErrors;    
      101.     
      102.         return (    
      103.             <div className="formDiv">    
      104.                 <h3 style={{ textAlign: "center" }} >Student Admission Form </ h3>    
      105.                 <div>    
      106.                     <form onSubmit={this.handleSubmit}>    
      107.                         <div>    
      108.                             <label htmlFor="studName">Name</label>    
      109.                             <input type="text" name="studName"    
      110.                                 value={this.state.studName}    
      111.                                 onChange={this.handleChange}    
      112.                                 placeholder="Your name.."    
      113.                                 className={studNameErr ? ' showError' : ''} />    
      114.                             {studNameErr &&    
      115.                                 <div style={{ color: "red", paddingBottom: 10 }}>{studNameErr}</div>    
      116.                             }    
      117.     
      118.                         </div>    
      119.                         <div>    
      120.                             <label htmlFor="emailId">Email Id</label>    
      121.                             <input type="text" name="emailId"    
      122.                                 value={this.state.emailId}    
      123.                                 onChange={this.handleChange}    
      124.                                 placeholder="Your email id.."    
      125.                                 className={emailIdErr ? ' showError' : ''} />    
      126.                             {emailIdErr &&    
      127.                                 <div style={{ color: "red", paddingBottom: 10 }}>{emailIdErr}</div>    
      128.                             }    
      129.     
      130.                         </div>    
      131.                         <div>    
      132.                             <label htmlFor="text">Birth Date</label>    
      133.                             <input type="text" name="dob"    
      134.                                 value={this.state.dob}    
      135.                                 onChange={this.handleChange}    
      136.                                 placeholder="DD/MM/YYYY.."    
      137.                                 className={dobErr ? ' showError' : ''} />    
      138.                             {dobErr &&    
      139.                                 <div style={{ color: "red", paddingBottom: 10 }}>{dobErr}</div>    
      140.                             }    
      141.                         </div>    
      142.                         <div>    
      143.                             <label htmlFor="gender">Gender</label>    
      144.                             <select name="gender" onChange={this.handleChange}    
      145.                                 className={genderErr ? ' showError' : ''}    
      146.                                 value={this.state.gender} >    
      147.                                 <option value="select">--Select--</option>    
      148.                                 <option value="male">Male</option>    
      149.                                 <option value="female">Female</option>    
      150.                                 <option value="female">Other</option>    
      151.                             </select>    
      152.                             {genderErr &&    
      153.                                 <div style={{ color: "red", paddingBottom: 10 }}>{genderErr}</div>    
      154.                             }    
      155.                         </div>    
      156.                         <div>    
      157.                             <label htmlFor="phoneNumber">Phone Number</label>    
      158.                             <input type="text" name="phoneNumber"    
      159.                                 onChange={this.handleChange}    
      160.                                 value={this.state.phoneNumber}    
      161.                                 placeholder="Your phone number.."    
      162.                                 className={phoneNumberErr ? ' showError' : ''} />    
      163.                             {phoneNumberErr &&    
      164.                                 <div style={{ color: "red", paddingBottom: 10 }}>{phoneNumberErr}</div>    
      165.                             }    
      166.                         </div>    
      167.                         <div>    
      168.                             <label htmlFor="city">City</label>    
      169.                             <select name="city"    
      170.                                 value={this.state.city}    
      171.                                 onChange={this.handleChange}    
      172.                                 className={cityErr ? ' showError' : ''} >    
      173.                                 <option value="select">--Select--</option>    
      174.                                 <option value="Pune">Pune</option>    
      175.                                 <option value="Mumbai">Mumbai</option>    
      176.                                 <option value="Hyderabad">Hyderabad</option>    
      177.                             </select>    
      178.                             {cityErr &&    
      179.                                 <div style={{ color: "red", paddingBottom: 10 }}>{cityErr}</div>    
      180.                             }    
      181.                         </div>    
      182.                         <input type="submit" value="Submit" />    
      183.                     </form>    
      184.                 </div>    
      185.             </div >    
      186.         )    
      187.     }    
      188. }    
      189.     
      190. export default AdmissionForm;
  5. After adding the above code into AdmissinForm.js file, Import AddmissinForm component into App.js file. 
    1. import React, { Component } from 'react';    
    2. import './App.css';    
    3. import AdmissionForm from './AdmissionForm';    
    4.     
    5. export default class App extends Component {    
    6.   render() {    
    7.     return (    
    8.       <div className="content">    
    9.         <AdmissionForm />    
    10.       </div >    
    11.     );    
    12.   }    
    13. }
  6. Now, run your application using following command

    npm start -o
  7. Above command will open browser and your output should be  like the below screen.

    Student registration form
  8. Enter invalid data to check/fire validations for this form/ input fields. If you enter invalid data into form input fields then it will show you validation messages like below.
    Student registration form with validation
  9. If you provide the correct data to form input fields and pressthe  submit button, then data/information gets stored successfully without prompting a validation message.

    Student registration form with valid data

    Successfully registration message
Summary
 
In this article, I have demonstrated  how to implement form validation in ReactJS.  Hopefully, it will help.