Quick Summary:
This comprehensive tutorial will explore how to implement form validations in React, leveraging React hooks and the third-party library React Hook Form. We will simplify the procedure of building form validation in React and the benefits of user input.
In today’s digital world, the demand for online marketplaces is booming. Many businesses are transitioning their operations online to meet this demand. Consequently, most websites and applications now incorporate forms. Implementing form validation is crucial for ensuring a smooth user experience and error-free data input.
This validation process verifies that user inputs meet the required criteria. With the integration of React hooks, form validation in React has become significantly more efficient. This tutorial aims to assist you in creating error-free inputs and user-friendly forms using React hooks. We’ll employ the React Hook Form library for validation purposes.
Form validation is a process that involves verifying user inputs to ensure they meet specified criteria. By employing form validation, users can be prevented from entering incorrect or incomplete data. This tutorial helps you create error-free inputs using React hooks, which ensure the development of a user-friendly form with appropriate validations.
In this tutorial, we will develop a form that enables users to input data. Following are the steps to create form validation in React. First, we will set up our components using the Create React App to kick-start our project. This tool enables us to start a new project by executing the below commands:
There are two essential components to create a form: Form.js and style.css. Form.js will handle form functionality and validation, and Style.css will define the visual styling of our webpage.
Below is the stylesheet for directly integrating it into your Form.js component for CSS specifics.
Form.js
import React from "react"; import "./styles.css"; function Form() { return ( export default Form;); }Contact Form
Styles.css
.container { max-width: 400px; margin: 0 auto; padding: 20px; border: 1px solid #ccc; border-radius: 5px; } .form-group { margin-bottom: 15px; } label { display: block; margin-bottom: 5px; } input[type="text"], input[type="email"], textarea { width: 100%; padding: 10px; border: 1px solid #ccc; border-radius: 5px; } button { padding: 10px 20px; background-color: #007bff; color: #fff; border: none; border-radius: 5px; cursor: pointer; } button:hover { background-color: #0056b3; } .error { display: block; color: #dc3545; font-size: 14px; margin-top: 5px; } .error::before { content: "\26A0"; /* Warning symbol */ margin-right: 5px; }
Hire Reactjs developers to Craft Dynamic User Interfaces that Enhance Your Online Presence Efficiently
With our Form now styled appropriately, we can integrate validation into the form. There are different styles to implement form validation using React Hooks. Let us simplify the process to implement form validation in React with the following steps:
const [formData, setFormData] = useState({ name: "", email: "", }); const [errors, setErrors] = useState({});
✔ formData: Within the formData state, two keys exist: ‘name’ and ’email’, initially configured as an object with blank ‘name’ and ’email’ fields. As the user inputs information, these values are stored within their corresponding keys in the formData state.
✔ Errors: Responsible for handling validation errors, initially set as an empty object.
const handleChange = (e) => { const { name, value } = e.target; setFormData((prevState) => ({ ...prevState, [name]: value, })); }; const handleSubmit = (e) => { e.preventDefault(); const validationErrors = validateForm(formData); if (Object.keys(validationErrors).length === 0) { // Form submission logic here console.log(formData); } else { setErrors(validationErrors); } };
✔ handleChange: Manages changes in input fields and updates the name and email states accordingly.
✔ handleSubmit: Triggers form submission and validation.
✔ validateForm: Validates the form, checking if the ‘name’ field is empty and if the ’email’ field is either empty or in a valid email format. It returns an object containing any validation errors found.
✔ isValidEmail: Performs basic email validation using a regular expression.
const validateForm = (data) => { let errors = {}; if (!data.name) { errors.name = "Name is required"; } if (!data.email.trim()) { errors.email = "Email is required"; } else if (!isValidEmail(data.email)) { errors.email = "Invalid email format"; } return errors; }; const isValidEmail = (email) => { // Basic email validation return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email); };
If the user attempts to submit the form without filling in the required fields, this validation function will display error messages such as “Name is required” and “Email is required”.
Below is the complete code provided regarding form validation using React hooks.
import React, { useState } from "react"; import "./styles.css"; function Form() { const [formData, setFormData] = useState({ name: "", email: "", }); const [errors, setErrors] = useState({}); const handleChange = (e) => { const { name, value } = e.target; setFormData((prevState) => ({ ...prevState, [name]: value, })); }; const handleSubmit = (e) => { e.preventDefault(); const validationErrors = validateForm(formData); if (Object.keys(validationErrors).length === 0) { // Form submission logic here console.log(formData); } else { setErrors(validationErrors); } }; const validateForm = (data) => { let errors = {}; if (!data.name) { errors.name = "Name is required"; } if (!data.email.trim()) { errors.email = "Email is required"; } else if (!isValidEmail(data.email)) { errors.email = "Invalid email format"; } return errors; }; const isValidEmail = (email) => { // Basic email validation return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email); }; return ( export default Form;); }Contact Form
Let’s delve deep into the steps for incorporating form validation using the React Hook Form library. We have explained everything you should know about form validation in the React Hook Form library, including installation, usage, and adding validation to the form.
A comprehensive explanation of this library is available in the NPM packages documentation. You can refer to this link for further information and details.
1. Import and destructure: Import the useForm hook and destructure the needed properties:
import { useForm } from 'react-hook-form'; const { register, handleSubmit, formState: { errors } } = useForm();
2. Register form fields: Use the register function to register each form field. Provide a key (name) and optional validation rules:
3. Create onSubmit handler: Define a function to handle form submission, receiving the form data as an argument:
4. Wrap form in handleSubmit: Wrap your form component with handleSubmit, passing the onSubmit function:
Here is the complete code provided for your reference, featuring the two fields that have been registered so far.
import React from "react"; import { useForm } from 'react-hook-form'; import './styles.css'; function Form() { const { register, handleSubmit, formState: { errors } } = useForm(); const onSubmit = (data) => { // Handle form submission logic here console.log('FormData', data); }; return ( export default Form;); }Contact Form
Here is the final step to validate our form. Let’s start with the first field name. We will use the required property.
1. Required field: Use the required property in the register to mark a field as mandatory. If the user submits the form with the name field empty, an error message will be triggered, which should be displayed below the input tag:
Here is an error message that you will get after following the above-mentioned code-
2. Email validation: Use the pattern property with a regular expression to validate the email fxormat:
3. Displaying error messages: Conditionally render error messages based on the errors object from formState:
{errors.email && errors.email.type === 'required' && ( Email is required )} {errors.email && errors.email.type === 'pattern' && ( Invalid email format )}
Following is the complete code provided for your understanding regarding form validation using the React Hook form:
import React from 'react'; import { useForm } from 'react-hook-form'; import './styles.css'; function Form() { const { register, handleSubmit, formState: { errors } } = useForm(); const onSubmit = (data) => { // Handle form submission logic here console.log('FormData', data); };return ( export default Form;); }Contact Form
In this comprehensive tutorial, we have discussed the details of form validation in React, utilizing both React hooks and the React Hook Form library. Understanding the importance of form validation in creating user-friendly interfaces and building a basic form structure using React.
Form library and demonstrate React Hook usage for form validation, installation, registration of form fields, submission handling, and error display. As a result, implementing robust form validation mechanisms in your React applications enhances user experience and data integrity. To learn more about form validation, you can contact a React JS development company for assistance or expertise.
React Hook Form simplifies form validation by providing built-in features like automatic error handling, validation rules, and cleaner syntax compared to manual validation with React Hooks.
Yes, React Hook Form allows you to define custom validation functions using the resolver prop with the register function. This enables you to implement complex validation logic specific to your needs.
Your Success Is Guaranteed !
We accelerate the release of digital product and guaranteed their success
We Use Slack, Jira & GitHub for Accurate Deployment and Effective Communication.