-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFront end
More file actions
94 lines (79 loc) · 2.42 KB
/
Front end
File metadata and controls
94 lines (79 loc) · 2.42 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import React, { useState } from "react";
function FormValidation() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [emailError, setEmailError] = useState("");
const [passwordError, setPasswordError] = useState("");
const validateEmail = (email) => {
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return regex.test(email);
};
const handleEmailChange = (e) => {
setEmail(e.target.value);
if (!validateEmail(e.target.value)) {
setEmailError("Invalid email format");
} else {
setEmailError("");
}
};
const handlePasswordChange = (e) => {
setPassword(e.target.value);
if (e.target.value.length < 6) {
setPasswordError("Password must be at least 6 characters");
} else {
setPasswordError("");
}
};
const isFormValid = email && password && !emailError && !passwordError;
const handleSubmit = (e) => {
e.preventDefault();
if (isFormValid) {
alert("Form submitted successfully!");
}
};
return (
<div style={{ maxWidth: "400px", margin: "40px auto", textAlign: "left" }}>
<h2>React Form Validation</h2>
<form onSubmit={handleSubmit}>
{/* Email Field */}
<div>
<label>Email:</label><br />
<input
type="email"
value={email}
onChange={handleEmailChange}
style={{ width: "100%", padding: "8px", marginTop: "5px" }}
/>
{emailError && <p style={{ color: "red" }}>{emailError}</p>}
</div>
{/* Password Field */}
<div style={{ marginTop: "15px" }}>
<label>Password:</label><br />
<input
type="password"
value={password}
onChange={handlePasswordChange}
style={{ width: "100%", padding: "8px", marginTop: "5px" }}
/>
{passwordError && <p style={{ color: "red" }}>{passwordError}</p>}
</div>
{/* Submit Button */}
<button
type="submit"
disabled={!isFormValid}
style={{
marginTop: "20px",
padding: "10px 20px",
backgroundColor: isFormValid ? "#007bff" : "#ccc",
color: "white",
border: "none",
cursor: isFormValid ? "pointer" : "not-allowed",
}}
>
Submit
</button>
</form>
</div>
);
}
export default FormValidation;