📌 INTRODUCTION
A login form is one of the most common components in web applications. It helps users enter their credentials and access a system securely.
In React, login forms are usually built using:
- useState hook
- Controlled components
- Form validation
In this program, we will develop a login form with validation using React state.
👉 This is a very important program for:
- Practical exams
- Viva questions
- Mini projects
- Placement preparation
📘 PROBLEM STATEMENT
👉 Develop a login form with validation using state in React.
💡 CONCEPTS USED
- React
useStateHook - Controlled Components
- Form Validation
- Event Handling
- Conditional Rendering
🧠 LOGIC EXPLANATION
The login form works as follows:
- Create state variables for email, password, and errors
- Bind input fields with state
- Validate fields when user submits the form
- Show error messages if fields are empty or invalid
- Show success message if validation passes
💻 PROGRAM CODE
Open src/App.js and write:
import { useState } from "react";
function App() {
const [formData, setFormData] = useState({
email: "",
password: ""
});
const [errors, setErrors] = useState({});
const [successMessage, setSuccessMessage] = useState("");
const handleChange = (e) => {
setFormData({
...formData,
[e.target.name]: e.target.value
});
setErrors({
...errors,
[e.target.name]: ""
});
setSuccessMessage("");
};
const validateForm = () => {
let newErrors = {};
if (!formData.email.trim()) {
newErrors.email = "Email is required";
} else if (!/\S+@\S+\.\S+/.test(formData.email)) {
newErrors.email = "Enter a valid email address";
}
if (!formData.password.trim()) {
newErrors.password = "Password is required";
} else if (formData.password.length < 6) {
newErrors.password = "Password must be at least 6 characters";
}
return newErrors;
};
const handleSubmit = (e) => {
e.preventDefault();
const validationErrors = validateForm();
setErrors(validationErrors);
if (Object.keys(validationErrors).length === 0) {
setSuccessMessage("Login successful!");
console.log("Login Data:", formData);
}
};
return (
<div style={styles.container}>
<form onSubmit={handleSubmit} style={styles.form}>
<h2>Login Form</h2>
<div style={styles.inputGroup}>
<label>Email:</label>
<input
type="text"
name="email"
value={formData.email}
onChange={handleChange}
placeholder="Enter your email"
style={styles.input}
/>
{errors.email && <p style={styles.error}>{errors.email}</p>}
</div>
<div style={styles.inputGroup}>
<label>Password:</label>
<input
type="password"
name="password"
value={formData.password}
onChange={handleChange}
placeholder="Enter your password"
style={styles.input}
/>
{errors.password && <p style={styles.error}>{errors.password}</p>}
</div>
<button type="submit" style={styles.button}>Login</button>
{successMessage && <p style={styles.success}>{successMessage}</p>}
</form>
</div>
);
}
const styles = {
container: {
display: "flex",
justifyContent: "center",
alignItems: "center",
minHeight: "100vh",
backgroundColor: "#f4f4f4"
},
form: {
backgroundColor: "#fff",
padding: "25px",
borderRadius: "10px",
boxShadow: "0 4px 8px rgba(0,0,0,0.1)",
width: "320px"
},
inputGroup: {
marginBottom: "15px",
textAlign: "left"
},
input: {
width: "100%",
padding: "8px",
marginTop: "5px",
borderRadius: "5px",
border: "1px solid #ccc"
},
button: {
width: "100%",
padding: "10px",
backgroundColor: "#007bff",
color: "#fff",
border: "none",
borderRadius: "5px",
cursor: "pointer"
},
error: {
color: "red",
fontSize: "14px",
marginTop: "5px"
},
success: {
color: "green",
marginTop: "15px",
textAlign: "center"
}
};
export default App;
🖥️ OUTPUT
Initial Form
Login Form
Email: [______________]
Password: [______________]
[ Login ]
If fields are empty
Email is required
Password is required
If email is invalid
Enter a valid email address
If password is too short
Password must be at least 6 characters
If all data is correct
Login successful!
🔍 STEP-BY-STEP EXPLANATION
1. Creating State
We use useState() to store:
- Password
- Error messages
- Success message
const [formData, setFormData] = useState({
email: "",
password: ""
});
2. Handling Input Changes
Whenever the user types, handleChange() updates the corresponding field.
[e.target.name]: e.target.value
This makes the code reusable for multiple inputs.
3. Form Validation
The validateForm() function checks:
- Whether email is empty
- Whether email format is valid
- Whether password is empty
- Whether password length is at least 6
4. Preventing Default Submission
React forms reload the page by default.
So we use:
e.preventDefault();
This keeps the app on the same page.
5. Displaying Errors
If validation fails, error messages are shown below the respective input fields.
{errors.email && <p>{errors.email}</p>}
🎯 WHY THIS PROGRAM IS IMPORTANT
This program teaches several key React concepts together:
- Controlled form inputs
- State management
- Validation logic
- Error display
- Clean user interface
It is very commonly asked in:
- React viva
- Practical exams
- Frontend interviews
⚡ ADVANCED VERSION IDEAS
You can improve this login form further by adding:
1. Show/Hide Password
Use state to toggle password visibility.
2. Remember Me Checkbox
Add a checkbox field using state.
3. API Integration
Send login details to a backend server.
4. Redirect after Login
Use React Router to navigate after successful login.
📚 REAL-WORLD USE CASE
This concept is used in:
- Admin login pages
- Student portals
- E-commerce accounts
- Banking applications
- Social media platforms
❓ VIVA QUESTIONS (IMPORTANT)
Q1. What is a controlled component in React?
👉 A controlled component is an input element whose value is controlled by React state.
Q2. Why is useState used in forms?
👉 It is used to store and update form values dynamically.
Q3. What is validation in a login form?
👉 Validation checks whether the entered data is correct and complete.
Q4. Why do we use preventDefault()?
👉 To stop the form from reloading the page after submit.
Q5. How do we show error messages in React?
👉 By storing errors in state and conditionally rendering them in JSX.
Q6. Why is password length checked?
👉 To ensure stronger and more valid user input.
Q7. Can we validate email format in React?
👉 Yes, using a regular expression or custom logic.
🔗 RELATED POSTS
👉 MCA 168 Full Stack Development Lab Programs List
👉 React Form Handling using useState – Program 16
👉 React Todo List App – Program 18
👉 React Simple Form Component – Program 14
📌 CONCLUSION
A login form with validation is one of the most essential programs in React. It teaches how to manage user input, validate data, and improve user experience.
👉 Practice this program well, because it is very useful in both academics and real-world projects.
Further Reading
How to Master Full Stack Development?
Spring Framework Practice Problems and Their Solutions
From Google to the World: The Story of Go Programming Language
Why Go? Understanding the Advantages of this Emerging Language
Creating and Executing Simple Programs in Go
20+ Interview Questions on Go Programming Language
100+ MCQs On Java Architecture
- Angular
- ASP.NET
- C
- C#
- C++
- CSS
- Dot Net Framework
- HTML
- IoT
- Java
- JavaScript
- Kotlin
- PHP
- Power Bi
- Python
- Scratch 3.0
- TypeScript
- VB.NET
