๐ฏ Learning Objectives
- Understand form validation importance
- Validate required fields
- Check email format
- Validate password strength
- Display error messages
- Prevent form submission on errors
๐ Why Form Validation?
Form validation ensures users enter correct data before submitting. This improves user experience and data quality by catching errors before they reach the server.
โ Common Validation Rules
- Required fields: Field cannot be empty
- Email format: Must contain @ and domain
- Password length: Minimum 8 characters
- Number validation: Must be a number
- Phone format: Correct phone number pattern
๐ Basic Validation Examples
1. Check if Field is Empty
function validateName() {
let name = document.getElementById("name").value;
if (name === "" || name === null) {
alert("Name is required!");
return false;
}
return true;
}
2. Email Validation
function validateEmail() {
let email = document.getElementById("email").value;
// Check if email contains @ and .
if (!email.includes("@") || !email.includes(".")) {
alert("Please enter a valid email!");
return false;
}
return true;
}
// Better email validation with regex
function isValidEmail(email) {
let emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailPattern.test(email);
}
3. Password Length Validation
function validatePassword() {
let password = document.getElementById("password").value;
if (password.length < 8) {
alert("Password must be at least 8 characters!");
return false;
}
return true;
}
๐จ Complete Form Validation Example
Registration Form
๐งช Live Demo Form
Try the Validation
๐ Validation Checklist
- โ Check if required fields are filled
- โ Validate email format with @ and domain
- โ Ensure password meets minimum length
- โ Confirm passwords match
- โ Display clear error messages
- โ Prevent form submission on errors
- โ Clear errors when form is valid
โ๏ธ Practice Exercises
- Create a login form with email and password validation
- Add age validation (must be 18 or older)
- Validate username (no spaces, min 5 characters)
- Create password strength indicator (weak/medium/strong)
- Build a contact form with all validation rules
โ Today's Deliverable
- โ form-validation.html with complete validation
- โ Required field validation
- โ Email format validation
- โ Password validation (minimum 8 characters)
- โ Password confirmation match
- โ Error messages displayed correctly
- โ Form prevents submission when invalid
- โ Working demo screenshot