Form Validation in Javascript

Form validation is essential for ensuring that user inputs meet specific criteria before submission. Here’s a basic example of how to perform form validation using both plain JavaScript and jQuery.

HTML

 <form id="myForm">
         <label for="name">Name:</label>
         <input type="text" id="name" name="name">
         <span id="nameError" style="color: red;"></span><br><br>
         <label for="email">Email:</label>
         <input type="email" id="email" name="email">
         <span id="emailError" style="color: red;"></span><br><br>
         <button type="submit">Submit</button>
      </form>

Javascript

 document.getElementById('myForm').addEventListener('submit', function(event) {
         // Clear previous errors
         document.getElementById('nameError').textContent = '';
         document.getElementById('emailError').textContent = '';
         
         // Get form values
         const name = document.getElementById('name').value.trim();
         const email = document.getElementById('email').value.trim();
         
         // Validate name
         if (name === '') {
             document.getElementById('nameError').textContent = 'Name is required.';
             event.preventDefault(); // Prevent form submission
             return;
         }
         
         // Validate email
         const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
         if (!emailPattern.test(email)) {
             document.getElementById('emailError').textContent = 'Invalid email address.';
             event.preventDefault(); // Prevent form submission
             return;
         }
         });

administrator

Leave a Reply

Your email address will not be published. Required fields are marked *