How to Validate Forms Data in React


We all know how important is doing the Validation of the Entered data before we do any operations using that data. In this article, We will understand how to Validate Forms in React.

Assuming that Our Form has total five inputs, Id, name, Location, Salary and EmailId. Now to this Form, We have to add Validation. From this forms input data, lets say we want to add Validation for Employee Name, Employee Location and Employee Email ID.

Lets define Our Validation rules before we proceed and write the code.

-Employee Name 

        1. Required

        2. MaxLength 20 Characters

-Employee Location

        1. Required

-Employee Email ID

        1. Required

        2. Email Pattern 

Now lets go ahead and create a function with a name as ValidateEmployee in our index.js file. This function will receive our employee object as input data. Lets create an object using which we will return error messages. Lets check if employee Name is having the data or not and if it doesnot have the data, set a New Property to our errors object and write the Error Message. If Employee Name is Entered, we have to check for maxlength validation. 

Now lets repeat the same for Location and for location we do only required field validation. And we do the same for Email ID plus we will do regular expression validation to check the Email ID format. From this function, we will return the errors object. 

Pass this function name to the validate Property of the useFormik function. Now lets go ahead and add the code required to display the Error Messages. It is important to display the messages only when user touch the input. To take advantage of touched, we can pass formik.handleBlur to each input's onBlur prop.

So after the input field, lets check if Name is input field is touched or not and if it is touched, check if the Name property has any errors or not. If Name has Errors, lets display the Error message in a span. Lets repeat the same for rest of the input elements.

Lets save these changes, navigate to the browser. As we keep entering the data we can see different error messages are being displayed here.

The Complete Code looks like below.

import React from 'react';
import ReactDOM from 'react-dom';
import {useFormik} from 'formik';

const validateEmployee = empData => {
  const errors = {};

  if (!empData.Name) {
    errors.Name = 'Please Enter Employee Name';
  } else if (empData.Name.length > 20) {
    errors.Name = 'Name cannot exceed 20 characters';
  }

  if (!empData.Location) {
    errors.Location = 'Please Enter Employee Location';
  } 

  if (!empData.EmailId) {
    errors.EmailId = 'Please Enter Email ID';
  } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(empData.EmailId)) {
    errors.EmailId = 'Invalid email address';
  }

  return errors;
};
const EmployeeComponent=()=>{
  const formik=useFormik({
    initialValues:{
      Id:'',
      Name:'',
      Location:'',
      Salary:'',
      EmailId:''
    },
    validate:validateEmployee,
    onSubmit:values=>{
      alert(JSON.stringify(values));
    }
  });

  return (
    <div>
      <h2>New Employee Form...</h2>
      
  <form onSubmit={formik.handleSubmit}>
        <p>
          <label htmlFor="Id">Employee ID : </label>
          <input type="text" name="Id" id="Id" value={formik.values.Id}
                  onChange={formik.handleChange}></input>  
        </p>
        <p>
           <label htmlFor="Name">Employee Name : </label>
           <input type="text" name="Name" id="Name" value={formik.values.Name}
                  onChange={formik.handleChange} onBlur={formik.handleBlur}></input>
                  {formik.touched.Name && formik.errors.Name ? <span style={{color:'red'}}>{formik.errors.Name}</span> : null}
                  
         </p>
         <p>
           <label htmlFor="Location">Employee Location : </label>
           <input type="text" name="Location" id="Location" value={formik.values.Location}
                  onChange={formik.handleChange} onBlur={formik.handleBlur}></input>
                  {formik.touched.Location && formik.errors.Location ? <span style={{color:'red'}}>{formik.errors.Location}</span> : null}
                 
         </p>
         <p>
           <label htmlFor="Salary">Employee Salary : </label>
           <input type="text" name="Salary" id="Salary" value={formik.values.Salary}
                  onChange={formik.handleChange}></input>                  
         </p>
         <p>
           <label htmlFor="EmailId">Employee Email ID : </label>
           <input type="text" name="EmailId" id="EmailId" value={formik.values.EmailId}
                  onChange={formik.handleChange} onBlur={formik.handleBlur}></input>
                  {formik.touched.EmailId && formik.errors.EmailId ? <span style={{color:'red'}}>{formik.errors.EmailId}</span> : null}
                 
         </p>
         <button type="submit">Create</button>
  </form>
    </div> 
  )
}

const element=<EmployeeComponent></EmployeeComponent>

ReactDOM.render(element,document.getElementById("root"));

Validation using Yup Library

By now we have seen how to write the validation code for our form inputs. But we are free to use any third party validation library available and do the form validation.

Formik's authors/a large portion of its users use Yup library for object schema validation. Since Formik authors/users love Yup so much, Formik has a special configuration option for Yup called validationSchema which will automatically transform Yup's validation errors messages into a pretty object whose keys match our forms input values.

 Lets navigate to our node js command prompt. Run a command to install yup into our project.

npm install yup –save

After the Installation is successful, run our project using 

Npm start 

Lets switch back to Visual studio code, lets delete all the validation code we have written. Lets import everything from yup. 

Add a new property called as validationSchema in useFormik function and assign the object function available. To this function, we pass our validation rules. First lets do it for name. we mention the data type followed by adding the validations for max length and required. Lets add the validations for Location and Email Id. 

Save these changes, Navigate to the browser and we can see the validation is happening for our form data as we enter the values.

If we see our input elements, we are writing so much of code to set values for different attributes like id, value, onchange, onblur. However, to save you time, useFormik() returns a helper method called formik.getFieldProps(). Lets go and modify our input elements to make use of it and to this method we will pass the Name of our input. We will do the same for rest of the input elements as well.

Save these changes, Navigate to the browser and we can see the behaviour we have earlier.

The Complete Code looks like below.

import React from 'react';

import ReactDOM from 'react-dom';

import {useFormik} from 'formik';

import * as yup from 'yup';



const EmployeeComponent=()=>{

  const formik=useFormik({

    initialValues:{

      Id:'',

      Name:'',

      Location:'',

      Salary:'',

      EmailId:''

    },

    validationSchema: yup.object({

      Name: yup.string()

        .max(20, 'Name should not exceed 20 Characters')

        .required('Please Enter Employee Name'),

      Location: yup.string()

        .required('Please Enter Employee Location'),

      EmailId: yup.string()

        .email('Invalid email address')

        .required('Please Enter Email Id'),

    }),

    onSubmit:values=>{

      alert(JSON.stringify(values));

    }

  });

  return (

    <div>

      <h2>New Employee Form...</h2>

  <form onSubmit={formik.handleSubmit}>

        <p>

          <label htmlFor="Id">Employee ID : </label>

          <input type="text" name="Id" {...formik.getFieldProps("Id")} ></input>  

        </p>

        <p>

           <label htmlFor="Name">Employee Name : </label>

           <input type="text" name="Name" {...formik.getFieldProps("Name")} ></input>

                  {formik.touched.Name && formik.errors.Name ? <span style={{color:'red'}}>{formik.errors.Name}</span> : null}
         </p>

         <p>

           <label htmlFor="Location">Employee Location : </label>

           <input type="text" name="Location" {...formik.getFieldProps("Location")} ></input>

                  {formik.touched.Location && formik.errors.Location ? <span style={{color:'red'}}>{formik.errors.Location}</span> : null}
         </p>

         <p>

           <label htmlFor="Salary">Employee Salary : </label>

           <input type="text" name="Salary" {...formik.getFieldProps("Salary")} ></input>                  

         </p>

         <p>

           <label htmlFor="EmailId">Employee Email ID : </label>

           <input type="text" name="EmailId" {...formik.getFieldProps("EmailId")} ></input>

                  {formik.touched.EmailId && formik.errors.EmailId ? <span style={{color:'red'}}>{formik.errors.EmailId}</span> : null}
         </p>

         <button type="submit">Create</button>

  </form>

    </div> 

  )

}

const element=<EmployeeComponent></EmployeeComponent>

ReactDOM.render(element,document.getElementById("root"));





© 2020 Pragimtech. All Rights Reserved.