Summary : This in-depth course will examine how to use React hooks and the third-party React Hook Form module to build form validations in React. We’ll streamline the process of implementing form validation in React and highlight the advantages of user input.
Online marketplace demand is rising in today’s digital age. To accommodate this need, a lot of businesses are moving their activities online. As such, forms are now included on the majority of websites and applications. For error-free data entry and a seamless user experience, form validation must be implemented.
This validation procedure confirms that user input satisfies the necessary requirements. React form validation is now much more efficient thanks to the incorporation of React hooks. The goal of this lesson is to help you use React hooks to create user-friendly forms and error-free inputs. For validation, we’ll use the React Hook Form module.
Form validation is the process of confirming that user inputs satisfy predetermined standards. Form validation can be used to stop users from entering inaccurate or missing data. This video teaches you how to use React hooks to build error-free inputs that guarantee the creation of a form that is easy to use and has the necessary validations.
We will create a form that lets users enter data in this lesson. The steps to create form validation in React are as follows. To get our project going, we will first build up our components using the Create React App. Using this program, we may launch a new project by running the following commands:
Form.js and style.css are the two prerequisites for creating a form. Form.js will manage the functionality and validity of the form, while Style.css will specify how our webpage will look.
The css to be immediately integrated into your Form can be found below.For CSS details, use the js component.
import React from "react";
import "./styles.css";
function Form() {
return (
Contact Form
);
}
export default Form;
.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;
}
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: Two keys, “name” and “email,” are present in the FormData state. Initially, the objects had blank “name” and “email” fields. These values are kept in the formData state within the appropriate keys as the user enters data.
✔ Errors: In charge of managing validation errors; initially assigned 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: Handles input field changes and modifies the email and name fields as necessary.
✏ handleSubmit: Starts the validation and submission of forms.
✏ validateForm: Verifies the form by determining whether the “name” and “email” fields are both empty or include valid email formats. Any validation errors discovered are returned in an object.
✏ isValidEmail: Makes use of a regular expression to carry out basic email validation.
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);
};
In the event that the user tries to submit the form without completing the necessary fields, this validation function will provide error messages like “Email required” and “Name 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 (
Contact Form
);
}
export default Form;
Let’s take a closer look at how to use the React Hook Form module to add form validation. Everything you need to know about installing, using, and applying validation to the form is covered in our explanation of the React Hook Form library’s form validation features.
npm install react-hook-form
You may get a detailed description of this library in the NPM packages documentation. For further specifics and information, click visit this page.
1. Import and destructure: Destructure the necessary properties after importing the useForm hook.
import { useForm } from 'react-hook-form';
const { register, handleSubmit, formState: { errors } } = useForm();
2. Register form fields: To register every form field, use the register function. Give a name for the key and any optional validation rules.
3. Create onSubmit handler: Create a function that will handle submitting forms and accept the form data as an argument:
const onSubmit = (data) => {
// Handle form submission logic here
console.log('FormData', data);
};
4. Wrap form in handleSubmit: Use handleSubmit to encapsulate your form component and pass the onSubmit function:
For your reference, the entire code is attached here, with the two fields that have been registered thus 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 (
Contact Form
);
}
export default Form;
This completes the process of validating our form. First, let’s address the name of the field. We’ll make advantage of the necessary asset.
1. Required field: To designate a field as required, use the required property in the register. An error message that appears beneath the input tag will be triggered if the user submits the form with the name field empty:
{errors.name && Name is required}
Here is an error message that you will get after following the above-mentioned code.
2. Email validation: To validate the email format, use the pattern property in conjunction with a regular expression:
3. Displaying error messages: Render error messages conditionally using the errors object from formState:
{errors.email && errors.email.type === 'required' && (
Email is required
)}
{errors.email && errors.email.type === 'pattern' && (
Invalid email format
)}
Here’s the full code for form validation using the React Hook form, which you can understand:
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 (
Contact Form
);
}
export default Form;
We have covered every aspect of form validation in React in this extensive tutorial, making use of the React Hook Form library in addition to React hooks. recognizing the value of form validation in designing user-friendly interfaces and use React to create a simple form structure.
Form library and show how to use React Hooks for installation, form field registration, submission handling, error display, and form validation. Therefore, incorporating strong form validation methods into your React apps improves data integrity and user experience. You can get support or knowledge regarding form validation by getting in touch with a React JS development business.
M | T | W | T | F | S | S |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 | 31 |
We are a team of artists. We provide professional services in the field of Mobile Applications, Web Applications and everything related to IT services. Turning to us for help once – you can no longer refuse.
© 2019 – 2022 | Made with ❤️ by App Ringer
Recent Comments