DEV Community

vidvatek
vidvatek

Posted on • Originally published at vidvatek.com

How To Validate Form in React JS

Are you ready to enhance your React.js skills by mastering the art of form validation in your web applications? Look no further! In this step-by-step guide, I will walk you through the process of implementing form validation in a React.js app.

We will cover essential form fields like Name, Email, Password, and Confirm Password, ensuring that the user-submitted data meets the required criteria.

Form validation plays a crucial role in creating user-friendly and error-free web forms. By validating user input, we can provide real-time feedback, improve data accuracy, and enhance the overall user experience.

Throughout this tutorial, we will explore how to create a React.js app, set up form fields, implement validation logic, and handle user interactions effectively.

To get started, make sure you have a basic understanding of React.js and JavaScript. Additionally, ensure that you have a React.js project set up on your machine.

With these prerequisites in place, we can dive into the exciting world of form validation in React.js!

So, let's embark on this journey together, empowering our web applications with robust form validation techniques. Get ready to take your React.js skills to the next level as we create dynamic and error-free forms.

Let's begin our exploration of form validation in React.js!

Step 1: Set Up a React.js Project

Create a new React.js project using create-react-app by executing the following command in your terminal.

npx create-react-app form-validation-app
Enter fullscreen mode Exit fullscreen mode

Navigate to the project directory.

cd form-validation-app
Enter fullscreen mode Exit fullscreen mode

Step 2: Create a Form Component

Create a new file called Form.js inside the src folder.

Inside the Form.js file, create a functional component named Form.

import React from 'react';

const Form = () => {
  return (
    <form>
      {/* Form fields will be added here */}
    </form>
  );
};

export default Form;
Enter fullscreen mode Exit fullscreen mode

Step 3: Setting Up Form State and Handling Form Input Changes
Inside the Form component, set up the initial state for the form fields and error messages.

const [formData, setFormData] = React.useState({
  name: '',
  email: '',
  password: '',
  confirmPassword: '',
});

const [formErrors, setFormErrors] = React.useState({
  name: '',
  email: '',
  password: '',
  confirmPassword: '',
});
Enter fullscreen mode Exit fullscreen mode

Create a function called handleInputChange to handle input changes.

const handleInputChange = (event) => {
  const { name, value } = event.target;

  setFormData((prevFormData) => ({
    ...prevFormData,
    [name]: value,
  }));
};
Enter fullscreen mode Exit fullscreen mode

Step 4: Implementing Form Validation

Add a function called validateForm to perform the form validation.

const validateForm = () => {
  let isValid = true;
  const errors = {};

  // Name validation
  if (formData.name.trim() === '') {
    errors.name = 'Name is required';
    isValid = false;
  }

  // Email validation
  // Use regular expressions or a validation library for a more thorough email validation
  if (formData.email.trim() === '') {
    errors.email = 'Email is required';
    isValid = false;
  }

  // Password validation
  if (formData.password.trim() === '') {
    errors.password = 'Password is required';
    isValid = false;
  }

  // Confirm password validation
  if (formData.confirmPassword.trim() === '') {
    errors.confirmPassword = 'Confirm Password is required';
    isValid = false;
  } else if (formData.password !== formData.confirmPassword) {
    errors.confirmPassword = 'Passwords do not match';
    isValid = false;
  }

  setFormErrors(errors);
  return isValid;
};
Enter fullscreen mode Exit fullscreen mode

Step 5: Handling Form Submission
Create a function called handleSubmit to handle form submission.

const handleSubmit = (event) => {
  event.preventDefault();

  if (validateForm()) {
    // Form is valid, perform further actions (e.g., submit to a server)
    console.log('Form is valid');
  } else {
    // Form is invalid, display error messages
    console.log('Form is invalid');
  }
};
Enter fullscreen mode Exit fullscreen mode

Step 6: Rendering the Form and Displaying Error Messages
Inside the return statement of the Form component, add the form HTML markup and error messages.

return (
  <div>
    <form onSubmit={handleSubmit}>
      <div>
        <label>Name:</label>
        <input
          type="text"
          name="name"
          value={formData.name}
          onChange={handleInputChange}
        />
        {formErrors.name && <span className="error">{formErrors.name}</span>}
      </div>
      {/* Repeat the above pattern for other form fields */}
      <button type="submit">Submit</button>
    </form>
  </div>
);
Enter fullscreen mode Exit fullscreen mode

Step 7: Run the Application
Start the development server by running the following command.

npm start
Enter fullscreen mode Exit fullscreen mode

This command will start the React development server and launch your application in your default web browser.

Conclusion

In this guide, we walked through the process of validating a form in a React.js application. By following the step-by-step instructions and incorporating the code examples provided, you can now implement form validation with fields like Name, Email, Password, and Confirm Password.

Top comments (0)