Skip to content

Commit 9219d9d

Browse files
committed
form validation
1 parent c2830d0 commit 9219d9d

File tree

1 file changed

+108
-0
lines changed

1 file changed

+108
-0
lines changed

form-validation/index.html

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8">
5+
<title>Simple Form Validation</title>
6+
<style>
7+
body {
8+
font-family: system-ui, Arial;
9+
background: #f9fafb;
10+
display: flex;
11+
justify-content: center;
12+
align-items: center;
13+
height: 100vh;
14+
}
15+
form {
16+
background: white;
17+
padding: 25px 30px;
18+
border-radius: 12px;
19+
box-shadow: 0 5px 20px rgba(0,0,0,0.1);
20+
width: 320px;
21+
}
22+
h3 {
23+
text-align: center;
24+
margin-bottom: 15px;
25+
}
26+
input {
27+
width: 100%;
28+
padding: 10px;
29+
margin-bottom: 12px;
30+
border: 1px solid #d1d5db;
31+
border-radius: 5px;
32+
}
33+
button {
34+
width: 100%;
35+
background: #2563eb;
36+
color: white;
37+
border: none;
38+
padding: 10px;
39+
border-radius: 6px;
40+
cursor: pointer;
41+
font-weight: bold;
42+
}
43+
button:hover {
44+
background: #1e40af;
45+
}
46+
p {
47+
color: red;
48+
font-size: 13px;
49+
margin: 0 0 10px;
50+
}
51+
</style>
52+
</head>
53+
<body>
54+
<form id="signupForm">
55+
<h3>📝 Sign Up</h3>
56+
57+
<input type="text" id="username" placeholder="Username">
58+
<p id="nameError"></p>
59+
60+
<input type="email" id="email" placeholder="Email">
61+
<p id="emailError"></p>
62+
63+
<input type="password" id="password" placeholder="Password">
64+
<p id="passError"></p>
65+
66+
<button type="submit">Submit</button>
67+
</form>
68+
69+
<script>
70+
const form = document.getElementById("signupForm");
71+
const username = document.getElementById("username");
72+
const email = document.getElementById("email");
73+
const password = document.getElementById("password");
74+
75+
form.addEventListener("submit", (e) => {
76+
e.preventDefault(); // stop form from reloading
77+
let valid = true;
78+
79+
// Reset previous error messages
80+
document.querySelectorAll("p").forEach(p => p.textContent = "");
81+
82+
// Username validation
83+
if (username.value.trim() === "") {
84+
document.getElementById("nameError").textContent = "Username is required.";
85+
valid = false;
86+
}
87+
88+
// Email validation (simple regex)
89+
const emailPattern = /^[^ ]+@[^ ]+\.[a-z]{2,3}$/;
90+
if (!email.value.match(emailPattern)) {
91+
document.getElementById("emailError").textContent = "Enter a valid email address.";
92+
valid = false;
93+
}
94+
95+
// Password validation
96+
if (password.value.length < 6) {
97+
document.getElementById("passError").textContent = "Password must be at least 6 characters.";
98+
valid = false;
99+
}
100+
101+
if (valid) {
102+
alert("🎉 Form submitted successfully!");
103+
form.reset();
104+
}
105+
});
106+
</script>
107+
</body>
108+
</html>

0 commit comments

Comments
 (0)