Mastering React Form Validation With Example

In this article, We learn how React form validation works and how you can add form validation in your React component with proper examples. I also, show you how you can add input text field validation and date field validation in your form.

 

React Form Validation

 

Validation can be implemented using the custom code or third-party libraries in this post we will see how you can add validation using react code.

 

What is React Form validation?

 

As a web developer you know the importance of form validation it asks the user to input correct data if the user didn’t enter the expected data and shows a validation message to the user.

There are different types of controls on the form like – Text, date, people picker, etc. The validation process ensures user inputs the correct values in these controls

So Let’s first create on form in React App and later we will add validation on form controls.

 

Creating a React Form

 

Create a React form that includes fields for First Name, Phone Number, Date of Birth (DOB), and a submit button.

 

import React, { useState } from 'react';

const MyForm = () => {
  // State variables for form fields
  const [firstName, setFirstName] = useState('');
  const [dob, setDOB] = useState('');
  const [phoneNumber, setPhoneNumber] = useState('');
  // Function to handle form submission
  const handleSubmit = (e) => {
    e.preventDefault();

    // You can perform further actions with the form data here
    console.log('Form submitted:');
  };

  return (
    <form onSubmit={handleSubmit}>
      {/* First Name */}
      <label>
        First Name:
        <input
          type="text"
          value={firstName}
          onChange={(e) => setFirstName(e.target.value)}
        />
      </label>
       {/* Date of Birth */}
      <label>
        Date of Birth:
        <input
          type="date"
          value={dob}
          onChange={(e) => setDOB(e.target.value)}
        />
      </label>
      {/* Phone Number */}
      <label>
        Phone Number:
        <input
          type="tel"
          value={phoneNumber}
          onChange={(e) => setPhoneNumber(e.target.value)}
        />
      </label>

      
      {/* Submit Button */}
      <button type="submit">Submit</button>
    </form>
  );
};

export default MyForm;

 

This React component (MyForm) uses the “useState” hook to manage the state of each form field. The handleSubmit function is triggered when the form is submitted, and you can customize its function to perform any actions you need with the form data.

 

Adding React Form Validation

 

I have updated the React form and added custom validation for First Name (it should be required), Date of Birth (required and less than the current date), and Phone Number (required and must take only integers). I’ve also included error messages to provide feedback to users when the input does not meet the requirement.

import React, { useState } from 'react';
import styled from 'styled-components';

// Styled components
const FormContainer = styled.form`
  max-width: 400px;
  margin: 0 auto;
`;
const FormContainerH1 = styled.h1`
  padding-bottom:20px;
`;
const FormControl = styled.label`
  display: block;
  margin-bottom: 15px;

  input {
    width: 100%;
    padding: 8px;
    margin-top: 5px;
    border: 1px solid #ccc;
    border-radius: 4px;
  }

  div {
    color: red;
    margin-top: 5px;
  }
`;

const SubmitButton = styled.button`
  background-color: #4caf50;
  color: white;
  padding: 10px 15px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
`;

const EmployeeForm = () => {
  // State variables for form fields and error messages
  const [firstName, setFirstName] = useState('');
  const [dob, setDOB] = useState('');
  const [phoneNumber, setPhoneNumber] = useState('');
  const [firstNameError, setFirstNameError] = useState('');
  const [dobError, setDOBError] = useState('');
  const [phoneNumberError, setPhoneNumberError] = useState('');

  // Function to handle form submission
  const handleSubmit = (e) => {
    e.preventDefault();

    // Validate the form fields before submission
    if (validateFirstName() && validateDOB() && validatePhoneNumber()) {
      // You can perform further actions with the form data here
      console.log('Form submitted:', { firstName, dob, phoneNumber });
    } else {
      // Display error messages if validation fails
      console.log('Form validation failed. Please check your inputs.');
    }
  };

  // Function to validate First Name
  const validateFirstName = () => {
    if (!firstName) {
      setFirstNameError('First Name is required');
      return false;
    }
    setFirstNameError('');
    return true;
  };

  // Function to validate Date of Birth
  const validateDOB = () => {
    if (!dob) {
      setDOBError('Date of Birth is required');
      return false;
    }

    const currentDate = new Date();
    const selectedDate = new Date(dob);

    if (selectedDate > currentDate) {
      setDOBError('Date of Birth must be less than the current date');
      return false;
    }

    setDOBError('');
    return true;
  };

  // Function to validate Phone Number
  const validatePhoneNumber = () => {
    if (!phoneNumber) {
      setPhoneNumberError('Phone Number is required');
      return false;
    }

    if (!/^\d+$/.test(phoneNumber)) {
      setPhoneNumberError('Phone Number must contain only integers');
      return false;
    }

    setPhoneNumberError('');
    return true;
  };

  return (
    <FormContainer onSubmit={handleSubmit}>
      <FormContainerH1>Employee Details</FormContainerH1>
      {/* First Name */}
      <FormControl>
        First Name:
        <input
          type="text"
          value={firstName}
          onChange={(e) => setFirstName(e.target.value)}
          onBlur={validateFirstName}
        />
        <div>{firstNameError}</div>
      </FormControl>

      {/* Date of Birth */}
      <FormControl>
        Date of Birth:
        <input
          type="date"
          value={dob}
          onChange={(e) => setDOB(e.target.value)}
          onBlur={validateDOB}
        />
        <div>{dobError}</div>
      </FormControl>

      {/* Phone Number */}
      <FormControl>
        Phone Number:
        <input
          type="text"
          value={phoneNumber}
          onChange={(e) => setPhoneNumber(e.target.value)}
          onBlur={validatePhoneNumber}
        />
        <div>{phoneNumberError}</div>
      </FormControl>

      {/* Submit Button */}
      <SubmitButton type="submit">Submit</SubmitButton>
    </FormContainer>
  );
};

export default EmployeeForm;

Now, the form includes custom validation for the specified fields, and error messages will be displayed accordingly. I have added minor styling using the React-styled components You can change the validation code and Styling based on your specific requirements.

Now run the app using npm-start and test the form validation whether it working as expected or not. See the below output –

 

React form validation example

Conclusion

This is how you can add validation on custom form controls using React. I hope now you can implement the form validation in your React App.