⚛️ React ? Forms ?️ Validation
Form validation ensures that user input meets expected criteria before submission. In React, validation can be implemented manually using component state and conditional rendering, or with helper libraries like Yup and Formik.
In this topic, you’ll learn how to implement:
React validation usually follows a simple pattern:
useState hooks.onSubmit or onChange).Libraries like Yup and Formik help manage complex validation and reduce boilerplate, but understanding manual validation with React state is the essential first step.
The simplest validation checks whether a required field has been filled in before allowing the form to submit. If the input is empty, an error message appears; otherwise, the form is accepted.
// Validate that the name field is not empty before submitting
import React, { useState } from "react";
function RequiredFieldForm() {
const [name, setName] = useState("");
const [error, setError] = useState("");
const handleSubmit = (e) => {
e.preventDefault();
if (name.trim() === "") {
setError("Name is required!");
} else {
setError("");
alert("Form submitted successfully!");
}
};
return (
<form onSubmit={handleSubmit}>
<h4>Required Field Example</h4>
<input
type="text"
className="form-control mb-2"
placeholder="Enter your name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
{error && <p className="text-danger">{error}</p>}
<button className="btn btn-primary">Submit</button>
</form>
);
}
export default RequiredFieldForm;
handleSubmit prevents the default form action.name.trim() is empty, an error message "Name is required!" is shown.You can validate email addresses using regular expressions (regex) to ensure they follow a valid pattern like username@domain.com.
// Validate email using a regular expression before submission
import React from "react";
function EmailValidationForm() {
const [email, setEmail] = React.useState("");
const [error, setError] = React.useState("");
const handleSubmit = (e) => {
e.preventDefault();
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
setError("Please enter a valid email address!");
} else {
setError("");
alert("Valid email submitted!");
}
};
return (
<form onSubmit={handleSubmit}>
<h4>Email Validation Example</h4>
<input
type="email"
className="form-control mb-2"
placeholder="Enter email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
{error && <p className="text-danger">{error}</p>}
<button className="btn btn-success">Validate</button>
</form>
);
}
export default EmailValidationForm;
emailRegex checks that the input contains text, an @, and a valid domain part.Passwords are often validated using rules like minimum length, presence of uppercase letters, digits, or special characters. Here we start with a basic length check.
// Ensure the password is strong enough before accepting it
import React from "react";
function PasswordValidationForm() {
const [password, setPassword] = React.useState("");
const [error, setError] = React.useState("");
const handleSubmit = (e) => {
e.preventDefault();
if (password.length < 8) {
setError("Password must be at least 8 characters long!");
} else {
setError("");
alert("Strong password!");
}
};
return (
<form onSubmit={handleSubmit}>
<h4>Password Validation Example</h4>
<input
type="password"
className="form-control mb-2"
placeholder="Enter password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
{error && <p className="text-danger">{error}</p>}
<button className="btn btn-warning">Check Password</button>
</form>
);
}
export default PasswordValidationForm;
Validation doesn’t have to happen only on submit. You can validate as the user types and display instant feedback about whether the current value is valid.
// Provide instant feedback while the user types a username
import React from "react";
function LiveValidationForm() {
const [username, setUsername] = React.useState("");
const [error, setError] = React.useState("");
const validate = (value) => {
if (value.length < 4) return "Username must be at least 4 characters!";
return "";
};
const handleChange = (e) => {
const value = e.target.value;
setUsername(value);
setError(validate(value));
};
return (
<div>
<h4>Live Validation Example</h4>
<input
type="text"
className="form-control mb-2"
placeholder="Enter username"
value={username}
onChange={handleChange}
/>
{error ? (
<p className="text-danger">{error}</p>
) : (
username && <p className="text-success">Looks good!</p>
)}
</div>
);
}
export default LiveValidationForm;
handleChange updates both username and error.validate().aria-invalid and aria-describedby on inputs to improve accessibility.Goal: Practice implementing client-side validation using React state so that users can submit only accurate and complete data.