Prevent Form Submission if Username and Password Are Empty in React
Last updated 6 months, 4 weeks ago | 296 views 75 5
First page link: Prevent Form Submission if Username and Password Are Empty Using JavaScript
Certainly! Here's a React version of preventing form submission when the username and password fields are empty using controlled components and client-side validation in JavaScript.
Prevent Form Submission if Username and Password Are Empty in React
In web applications, it's important to validate forms on the client side before submission to avoid unnecessary server requests. React provides an intuitive way to manage form input using state and event handling.
✅ What You'll Learn
-
Create a login form in React
-
Use
useStateto manage form values -
Prevent submission if username or password is blank
-
Display error messages dynamically
Step-by-Step Code Example
import React, { useState } from "react";
function LoginForm() {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState("");
const handleSubmit = (e) => {
e.preventDefault(); // prevent default form submission
if (username.trim() === "" || password.trim() === "") {
setError("Username and password cannot be empty.");
return;
}
setError(""); // clear error
// Proceed with form submission (e.g., API call)
console.log("Form submitted!", { username, password });
};
return (
<div style={{ maxWidth: "400px", margin: "50px auto" }}>
<h2>Login</h2>
<form onSubmit={handleSubmit}>
<div style={{ marginBottom: "10px" }}>
<label>Username:</label>
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
style={{ width: "100%", padding: "8px" }}
/>
</div>
<div style={{ marginBottom: "10px" }}>
<label>Password:</label>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
style={{ width: "100%", padding: "8px" }}
/>
</div>
{error && <p style={{ color: "red" }}>{error}</p>}
<button type="submit" style={{ padding: "10px 20px" }}>
Login
</button>
</form>
</div>
);
}
export default LoginForm;
Explanation
-
useStatetracks input values and errors. -
handleSubmitintercepts the form submission. -
If fields are blank, an error message is shown and submission is stopped.
-
Otherwise, you can proceed with your logic like an API call or redirect.
Tips
-
Always trim input to ignore spaces.
-
Consider disabling the button until inputs are valid.
-
Use
onBluror real-time validation for better UX.
⚠️ Common Pitfalls
| Pitfall | Solution |
|---|---|
| Form submits even when empty | Use e.preventDefault() properly |
| Whitespace-only inputs allowed | Use trim() |
| Error doesn’t show | Ensure setError() is triggered |