Forms are essential for collecting user input on websites. JavaScript allows you to validate form data before submitting it to the server, improving user experience and preventing errors.
This blog explains how to validate forms using JavaScript with practical examples.
⭐ 1. Accessing Form Elements
You can access form elements using the DOM:
<form id="myForm">
<input type="text" id="username" name="username">
<input type="email" id="email" name="email">
<button type="submit">Submit</button>
</form>
let form = document.getElementById("myForm");
let username = document.getElementById("username");
let email = document.getElementById("email");
⭐ 2. Basic Form Validation
Check if a field is empty before submitting.
form.addEventListener("submit", function(event) {
if(username.value === "") {
alert("Username is required");
event.preventDefault(); // prevent form submission
}
});
⭐ 3. Validating Email
Use regular expressions to check the email format.
form.addEventListener("submit", function(event) {
let emailPattern = /^[^ ]+@[^ ]+\.[a-z]{2,3}$/;
if(!email.value.match(emailPattern)) {
alert("Enter a valid email");
event.preventDefault();
}
});
⭐ 4. Password Validation Example
Check for minimum length and characters.
let password = document.getElementById("password");
form.addEventListener("submit", function(event) {
if(password.value.length < 6){
alert("Password must be at least 6 characters");
event.preventDefault();
}
});
⭐ 5. Real-time Validation (Optional)
Validate fields as the user types.
username.addEventListener("input", function(){
if(username.value.length < 3){
username.style.borderColor = "red";
} else {
username.style.borderColor = "green";
}
});
⭐ 6. Combining Multiple Validations
form.addEventListener("submit", function(event) {
if(username.value === "" || !email.value.match(emailPattern)) {
alert("Please fill in all fields correctly");
event.preventDefault();
}
});
⭐ 7. Why Form Validation Matters
- Prevents incorrect or incomplete data submission
- Enhances user experience
- Reduces server-side errors
- Ensures secure input handling
⭐ Conclusion
JavaScript form validation is a powerful tool for building interactive and secure web applications. By validating inputs in real-time or before submission, you can improve user experience and reduce server-side errors.
📌 Citations
🔗 View other articles about Javascript:
https://savanka.com/category/learn/js/
🔗 External Javascript Documentation:
https://www.w3schools.com/js/