Module 37 : Preventing Default and Form Validation.
📚 Section 1: What is event.preventDefault()?
✅ Definition:
event.preventDefault() is a method used to stop the default action of an element from happening.
✅ Common Use Case:
Preventing form submission
Preventing a link from navigating
Preventing default behaviors in keyboard events
🧠 Syntax:
javascript code
event.preventDefault();
1: Preventing Link Navigation
html code
<a href="https://google.com" id="myLink">Go to Google</a> <script> document.getElementById("myLink").addEventListener("click", function(event){ event.preventDefault(); alert("Default action prevented!"); }); </script>
💡 Explanation:
Clicking the link won’t open Google.
Instead, an alert is shown.
Preventing default is useful to add custom logic before allowing the default action.
📚 Section 2: Introduction to Form Validation
🔍 What is Form Validation?
Form validation ensures that users input data in the correct format before submission.
🔄 Types of Validation:
Client-Side Validation (Using JavaScript)
Server-Side Validation (Using Backend Logic)
🎯 Why Use Client-Side Validation?
Provides immediate feedback
Reduces server load
Improves user experience
📘 Section 3: Form Validation
✅ HTML Form:
html code
<form id="registrationForm"> <input type="text" id="username" placeholder="Username" required /> <input type="email" id="email" placeholder="Email" required /> <input type="password" id="password" placeholder="Password" required /> <button type="submit">Register</button> <p id="error-message" style="color:red;"></p> </form>
✅ JavaScript:
javascript code
document.getElementById("registrationForm").addEventListener("submit", function(event) { event.preventDefault(); // Stop form from submitting let username = document.getElementById("username").value.trim(); let email = document.getElementById("email").value.trim(); let password = document.getElementById("password").value.trim(); let errorMessage = document.getElementById("error-message"); if (username === "" || email === "" || password === "") { errorMessage.textContent = "All fields are required."; return; } if (!email.includes("@")) { errorMessage.textContent = "Invalid email format."; return; } if (password.length < 6) { errorMessage.textContent = "Password must be at least 6 characters."; return; } // Passed all checks errorMessage.textContent = ""; alert("Form submitted successfully!"); });
Exercise Form Validation
Objective:
Build a registration form that validates:
Empty fields
Valid email
Password length
Create an HTML file with a form.
Add JavaScript to prevent default submission.
Display error messages.
Add color styles for feedback.
🔍 Extension:
Highlight fields with red border if invalid
Use regex to validate email
Add confirm password match validation
🎓 Advanced Validation using Regex
javascript code
function isValidEmail(email) { let regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; return regex.test(email); }
Replace !email.includes("@") with:
javascript code
if (!isValidEmail(email)) { errorMessage.textContent = "Please enter a valid email address."; return; }
📊 Research Insights: Why Validation Matters
🔍 UX Research
Users trust forms that give clear, feedback.
Preventing bad data improves conversion rates and reduces frustration.
Validation should not just block – it should guide.
🔐 Security Note:
Client-side validation should never replace server-side validation.
Practices
Do
Don't
Use clear error messages
Don’t rely only on HTML5 validation
Highlight invalid fields visually
Don’t validate only on submit
Combine preventDefault() with checks
Don’t allow form to submit with bad data
Add success/failure feedback
Don’t leave user confused about what went wrong
Methods Recap
1. preventDefault() to block form auto-submit
2. Manual validation logic per input field
3. Clear and styled feedback for better UX
4. Regex for complex patterns like email
Summary
event.preventDefault() is essential for intercepting form behavior.
JavaScript form validation improves interactivity and ensures data quality.
Use both HTML and JS together for optimal form experience.
Practice dynamic validation with error messages and field highlights.
Always include server-side validation for security.
Steps
Open Code Editor (VSCode)
Create form-validation.html
Add the form and JavaScript code above.
Test with:
Empty fields
Invalid email
Short password
Modify and test live feedback (e.g., highlight fields)
🧠 Reflection Questions
Why is preventDefault() used during form submission?
How can dynamic feedback improve UX?
How would you implement password strength validation?
No comments:
Post a Comment