• Articles
  • Tutorials
  • Interview Questions

How to Use React Form Validation

How to Use React Form Validation

Table of content

Show More

In this blog, we will guide you through the steps of integrating form validation into a React application, including how to create a React form, validation of the form without an external library, form validation through React hooks, and using third-party libraries.

To learn more about Forms in React JS, watch our react form validation tutorial:

Video Thumbnail

What is Form Validation in React?

In React, form validation is the practice of verifying that user-entered data in a form adheres to specific requirements or conditions before it’s sent to a server or used in subsequent actions. It is a crucial aspect of web application development, serving to uphold data accuracy and enhance the user’s interaction. React, a widely used JavaScript library for crafting user interfaces, offers a versatile and effective approach to incorporating form validation.

Get more knowledge of how to implement React, react form validation best practices and react form validation custom hooks through our React JS Course.

How to Create a React Form

How to Create a React Form

To create a basic React form, we can start by using the <form> element and various form input components like <input>, <textarea>, and <button>. We’ll also need to handle form submission and input changes using React state and event handlers.

Here, for the react form validation example, we will create a React form with an input and submit button. This code is a React component that defines a simple registration form using functional components and the useState hook.

import React, { useState } from "react";
import "./App.css";
const RegistrationForm = () => {
const [emailInput, setEmailInput] = useState("");
const [passwordInput, setPasswordInput] = useState("");
const handleFormSubmit = (e) => {
e.preventDefault();
alert("The email address and password are " + emailInput + " and " + passwordInput + " respectively.");
};
return (
<div className="registration-form">
<form onSubmit={handleFormSubmit} autoComplete="off">
<h1>Register</h1>
<div className="form-input">
<label>Email</label>
<input
type="email"
name="email"
value={emailInput}
placeholder="Enter your email..."
onChange={(e) => setEmailInput(e.target.value)}
/>
</div>
<div className="form-input">
<label>Password</label>
<input
type="password"
name="password"
value={passwordInput}
placeholder="Enter a strong password..."
onChange={(e) => setPasswordInput(e.target.value)}
/>
</div>
<button>Submit</button>
</form>
</div>
);
};
export default RegistrationForm;

We have created this component, which represents a basic registration form in React, allowing users to enter their email and password. When the user submits the form, an alert displays the entered values.

Form Output

You can now sign up for our online, instructor-led Full Stack Developer course to gain proficiency in essential web development languages like HTML, CSS, and JavaScript.

Form Validation without an External Library

Form Validation without an External Library

In React, we can perform form validation without an external library by utilizing the built-in form handling and state management features. We can create custom validation functions and update the component’s state to display error messages based on the validation results.

To implement form validation without using an external library in the provided code, we can add custom validation logic within the handleFormSubmit function. We can change the function accordingly.

const RegistrationForm = () => {
const [emailInput, setEmailInput] = useState("");
const [passwordInput, setPasswordInput] = useState("");
const [emailError, setEmailError] = useState("");
const [passwordError, setPasswordError] = useState("");
const handleFormSubmit = (e) => {
e.preventDefault();
// Reset previous error messages
setEmailError("");
setPasswordError("");
// Password validation
const passwordPattern = /^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{8,20}$/;
if (!passwordPattern.test(passwordInput)) {
setPasswordError("Password requirements: 8-20 characters, 1 number, 1 letter, 1 symbol.");
return;
}
// If both email and password are valid, proceed with form submission
alert(
"Registration successful!\nEmail: " + emailInput + "\nPassword: " + passwordInput
);
};

Now, let’s break down the code: 

const passwordPattern = /^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{8,20}$/;

This code establishes a specific pattern using a regular expression to validate passwords, which is explained as follows:

  • ^ and $ indicate the starting and ending of the string.
  • (?=.*[0-9]) is a condition that checks if the string has at least one digit (0-9).
  • (?=.*[a-zA-Z]) checks if the string contains at least one letter (a-zA-Z).
  • (?=.*[!@#$%^&*]) checks if the string includes at least one special character from the set !@#$%^&*.
  • [a-zA-Z0-9!@#$%^&*]{8,20} matches a string that’s made up of a combination of letters, digits, and the specified special characters. This string must be between 8 and 20 characters long.

These regular expressions help enforce password format requirements in the form. If the user’s input does not meet these criteria, appropriate error messages are displayed.

Discover the process of installing React on a Windows operating system as well.

Get 100% Hike!

Master Most in Demand Skills Now!

Form Validation with React Hook Form

Form Validation with React Hook Form

Instead of manually creating complex validation logic, we can use a react form validation library like react-hook-form to simplify the process. React-hook-form provides a straightforward and effective way to manage form validation, which includes error handling and input validation.

To use react form validation hooks in the provided React registration form, react-hook-form can be used as following:

Install the react-hook-form library.

npm install react-hook-form

We can now import the “useForm” hook and employ it to control our form state and validation, as shown below:

import React from "react";
import { useForm } from "react-hook-form";
import "./App.css";
const RegistrationForm = () => {
const { handleSubmit, register, formState: { errors } } = useForm();
const onSubmit = values => {
alert(values.email + " " + values.password);
};
return (
<div className="registration-form">
<form onSubmit={handleSubmit(onSubmit)}>
<h1>Register</h1>
<div className="formInput">
<label>Email</label>
<input
type="email"
{...register("email", {
required: "Required",
pattern: {
value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
message: "Invalid email address"
}
})}
/>
{errors.email && errors.email.message}
</div>
<div className="formInput">
<label>Password</label>
<input
type="password"
{...register("password", {
required: "Required",
pattern: {
value: /^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{8,20}$/,
message: "Password requirements: 8-20 characters, 1 number, 1 letter, 1 symbol."
}
})}
/>
{errors.password && errors.password.message}
</div>
<button type="submit">Submit</button>
</form>
</div>
);
};
export default RegistrationForm;

Let’s dive into the code and break down the things:

  • In this code snippet, the useForm hook from a library is used to manage the state of a form, including validation errors and form data.
  • The form has input fields for password and email. These fields utilize the register method from the useForm hook to register each field with its specific validation rules.
  • If validation errors are detected, they are stored in an errors object, and the corresponding error message is shown to the user.
  • When the user submits the form, the handleSubmit function from the useForm hook is triggered. This function takes an onSubmit function as an argument.
  • The onSubmit function receives the form values and shows an alert message containing the given email and password values.
Output of Wrong Password

Consider pursuing a React JS certification? Here’s an opportunity to enroll in React JS training in Bangalore!

Form Validation with Third-Party Libraries

Form Validation with Third-Party Libraries

Form validation is essential to ensuring the accuracy and completeness of the data added to a form. While custom validation logic can be created in React, using libraries like react-hook-form simplifies the process and offers a submission experience that is more user-friendly.

Other npm packages, such as Zod and Formik, offer additional features to enhance form validation. Let us take a look at both npm packages.

  • Formik is a popular npm package in the React ecosystem that provides a robust set of tools for managing and validating forms. It simplifies form handling by offering features like form state management, input validation, and error handling. Formik seamlessly integrates with React components, allowing you to easily create and maintain complex forms with less boilerplate code. It also supports asynchronous form submissions, making it suitable for handling server interactions and complex form workflows.
  • Zod, on the other hand, is a powerful TypeScript-first validation library. It specializes in runtime type checking and validation for data, including form input. Zod enables you to define strict data schemas using TypeScript’s type system and provides a runtime validation layer to ensure that your data adheres to those schemas. This makes it an excellent choice for form validation, ensuring that the data submitted through your forms is not only structurally correct but also meets your application’s specific validation criteria.

Preparing for a Job Interview? Check out our blog on most asked React Interview Questions for Experienced!

Conclusion

In conclusion, managing user input and form validation are essential aspects of creating interactive web applications in React. You can implement form validation manually, use libraries like “react-hook-form” for a more convenient approach, or explore other third-party options like Formik and Zod. Regardless of the method chosen, prioritizing user-friendly validation processes is key to delivering a positive user experience in your web application.

We hope this article helps you gain knowledge of Full Stack developer course. If you are looking to learn Full Stack developer course with placement guarantee in a systematic manner from top faculty & Industry experts then you can enroll to our Full Stack development course.

FAQs

What are the Three Types of Form Validation?

There are three main ways to check if the stuff you put into a form is correct: a. Client-Side Validation: It’s like a quick check on your computer or phone to see if you left things blank or if your email looks right. b. Server-Side Validation: After you hit the “send” button, the website’s computer does another check to catch bigger problems, like repeated info or security issues. c. Database Validation: This is the boss of checks, happening inside the computer storage. It makes sure everything follows strict rules, such as unique usernames.

How to Validate Form with regex?

You can use “regex” patterns to make sure your text inputs are correct. For example, you can use a regex pattern to check if an email looks like an email. If it doesn’t match the pattern, you can show an error.

What is useForm()?

useForm() is a function in React libraries like React Hook Form or Formik. It simplifies form handling by managing form state, handling submission, and providing methods for input validation. You use it like const { register, handleSubmit, errors } = useForm();.

How do I Validate a Date in ReactJS?

To check if a date in ReactJS is okay, you can use special libraries or regular JavaScript. You can try to turn the date into a proper date and then see if it’s not too far in the past or the future. If it’s not right, you can tell the user to fix it. This way, you make sure you get the right date in your React app.

What is React Form Validation Performance?

React form validation performance refers to how efficiently a React application handles the validation of user input in forms. It involves ensuring that the validation process doesn’t cause slowdowns or delays in the user interface.

Course Schedule

Name Date Details
Web Development Courses 16 Nov 2024(Sat-Sun) Weekend Batch View Details
23 Nov 2024(Sat-Sun) Weekend Batch
30 Nov 2024(Sat-Sun) Weekend Batch

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full-Stack-Development.jpg