Form Validation in JavaScript
Form validation ensures that users input the correct data in forms before submitting them.
Basic Form Validation
We can use JavaScript to check if a form field is empty:
function validateForm() {
let name = document.getElementById("name").value;
if (name === "") {
alert("Name must be filled out");
return false;
}
}
Using HTML5 Validation
HTML5 provides attributes like required, minlength, and maxlength for simple validation.
Activity
Try It Yourself!
Create a form with fields for name and email. Add basic validation to check if these fields are filled.
Quiz
Quick Quiz
- What does form validation do?
- How do you prevent a form from submitting if a field is empty?
- What is the
requiredattribute in HTML5?
Answers: Ensures correct input; return false in JavaScript; makes a field mandatory.