validation

Form Validation in JavaScript

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

  1. What does form validation do?
  2. How do you prevent a form from submitting if a field is empty?
  3. What is the required attribute in HTML5?

Answers: Ensures correct input; return false in JavaScript; makes a field mandatory.