Form Validation in React
Learn how to validate user input, display error messages, and handle invalid form data in React.
1. Introduction to Form Validation
Form validation checks whether the information entered by a user meets the required conditions before a form is submitted. It helps prevent missing or incorrectly formatted information.
In React, validation can be performed using state, conditional rendering, and event handlers. For example, a registration form may require a student name and a valid email address.
2. Required Field Validation
Required field validation checks whether the user has entered a value. We can use the trim() method to remove leading and trailing spaces before checking the input.
Example
import { useState } from "react";
function NameValidation() {
const [name, setName] = useState("");
const [error, setError] = useState("");
function handleSubmit(event) {
event.preventDefault();
if (name.trim() === "") {
setError("Name is required.");
return;
}
setError("");
alert("Form submitted successfully!");
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="name">Student Name:</label>
<input
id="name"
value={name}
onChange={(event) => {
setName(event.target.value);
setError("");
}}
/>
{error && <p>{error}</p>}
<button type="submit">Submit</button>
</form>
);
}
export default NameValidation;
Expected Output
Name is required.
If the user submits the form without entering a name, the error message is displayed. When a name is entered, the error is cleared.
3. Email Validation
Email validation checks whether an entered email address follows an expected format. The following example uses a simple regular expression for basic client-side checking.
Example
import { useState } from "react";
function EmailValidation() {
const [email, setEmail] = useState("");
const [error, setError] = useState("");
function handleSubmit(event) {
event.preventDefault();
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailPattern.test(email)) {
setError("Please enter a valid email address.");
return;
}
setError("");
alert("Email is valid!");
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="email">Email Address:</label>
<input
id="email"
type="email"
value={email}
onChange={(event) => {
setEmail(event.target.value);
setError("");
}}
/>
{error && <p>{error}</p>}
<button type="submit">Validate Email</button>
</form>
);
}
export default EmailValidation;
Expected Output
Please enter a valid email address.
If the email does not match the expected format, the component displays an error message. This is a basic format check, not proof that the address exists.
4. Password Length Validation
Password validation can check whether a password meets a minimum length requirement. The example below requires at least eight characters.
Example
import { useState } from "react";
function PasswordValidation() {
const [password, setPassword] = useState("");
const [error, setError] = useState("");
function handleSubmit(event) {
event.preventDefault();
if (password.length < 8) {
setError("Password must contain at least 8 characters.");
return;
}
setError("");
alert("Password length is valid.");
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="password">Password:</label>
<input
id="password"
type="password"
value={password}
onChange={(event) => {
setPassword(event.target.value);
setError("");
}}
/>
{error && <p>{error}</p>}
<button type="submit">Check Password</button>
</form>
);
}
export default PasswordValidation;
Expected Output
Password must contain at least 8 characters.
5. Validating Multiple Fields
A form may need to validate multiple fields before submission. We can check each field and store its validation message in state.
Example: Student Registration
import { useState } from "react";
function StudentRegistration() {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [errors, setErrors] = useState({});
function handleSubmit(event) {
event.preventDefault();
const newErrors = {};
if (name.trim() === "") {
newErrors.name = "Name is required.";
}
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailPattern.test(email)) {
newErrors.email = "Enter a valid email address.";
}
setErrors(newErrors);
if (Object.keys(newErrors).length === 0) {
alert("Registration form is valid.");
}
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="name">Student Name:</label>
<input
id="name"
value={name}
onChange={(event) => setName(event.target.value)}
/>
{errors.name && <p>{errors.name}</p>}
<label htmlFor="email">Email Address:</label>
<input
id="email"
type="email"
value={email}
onChange={(event) => setEmail(event.target.value)}
/>
{errors.email && <p>{errors.email}</p>}
<button type="submit">Register</button>
</form>
);
}
export default StudentRegistration;
Expected Output
Name is required.
Enter a valid email address.
The form checks both fields and stores any errors in the errors object. Submission succeeds only when no validation errors remain.
6. CIIT Training Institute Registration Example
Samadhan wants to register for a course at CIIT Training Institute. This example validates the student's name and email before showing a successful submission message.
Example
import { useState } from "react";
function CIITRegistration() {
const [name, setName] = useState("Samadhan");
const [email, setEmail] = useState("");
const [message, setMessage] = useState("");
function handleSubmit(event) {
event.preventDefault();
if (name.trim() === "") {
setMessage("Please enter your name.");
return;
}
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailPattern.test(email)) {
setMessage("Please enter a valid email.");
return;
}
setMessage(
"Thank you, " + name +
"! Your form passed client-side validation."
);
}
return (
<form onSubmit={handleSubmit}>
<h2>CIIT Training Institute</h2>
<label htmlFor="studentName">Student Name:</label>
<input
id="studentName"
value={name}
onChange={(event) => setName(event.target.value)}
/>
<label htmlFor="studentEmail">Email Address:</label>
<input
id="studentEmail"
type="email"
value={email}
onChange={(event) => setEmail(event.target.value)}
/>
<button type="submit">Submit Registration</button>
{message && <p>{message}</p>}
</form>
);
}
export default CIITRegistration;
Expected Output
Thank you, Samadhan! Your form passed client-side validation.
When valid values are entered, the form displays a confirmation message. This demonstration does not save the registration to a database or submit it to CIIT Training Institute.
7. Displaying Error and Success Messages
Conditional rendering allows React to display an error message only when validation fails. A success message can be displayed when all required checks pass.
Example
{error && (
<p className="error-message">
{error}
</p>
)}
{success && (
<p className="success-message">
{success}
</p>
)}
When error contains a message, React renders the error paragraph. When success contains a message, React renders the success paragraph.
8. Common Mistakes
Mistake 1: Not Preventing Default Submission
function handleSubmit(event) {
if (name.trim() === "") {
setError("Name is required.");
}
}
Without preventDefault(), a browser form submission may reload or navigate away from the page before the expected React behavior completes.
Correct Code
function handleSubmit(event) {
event.preventDefault();
if (name.trim() === "") {
setError("Name is required.");
return;
}
}
Mistake 2: Checking Only for an Empty String
if (name === "") {
setError("Name is required.");
}
A value containing only spaces is not an empty string. Using trim() checks whether any non-whitespace text remains.
Correct Code
if (name.trim() === "") {
setError("Name is required.");
}
Mistake 3: Showing Success Despite Validation Errors
setErrors(newErrors);
alert("Form submitted successfully!");
The form should not show success when validation has failed. Check the validation result before proceeding.
Correct Code
if (Object.keys(newErrors).length === 0) {
alert("Form submitted successfully!");
}
9. Practice Tasks
Complete these tasks to practise form validation in React.
Summary
Form validation checks user input before a form is processed. React can use state, event handlers, and conditional rendering to validate required fields, check email formats, enforce password length rules, and display error or success messages. Multiple field errors can be stored in an object and checked before allowing a successful result. Client-side validation improves usability, while server-side validation remains necessary for application security and data integrity. These techniques can be practised through student registration forms at CIIT Training Institute.