How to validate a form using JavaScript and prevent submission on error?

To validate a form using JavaScript and prevent submission on error, you can follow these steps:

  1. Add an onsubmit attribute to the HTML form element.
  2. Create a JavaScript function that will handle the form validation.
  3. Inside the validation function, use the event.preventDefault() method to prevent form submission if there are any errors.
  4. Implement the necessary form validation logic, such as checking if required fields are empty, validating email format, checking password strength, etc.
  5. If an error occurs during validation, display an error message to the user and possibly highlight the invalid fields.
  6. If all the validation checks pass, allow the form to submit by returning true from the validation function.

Here's an example to illustrate the process:

HTML:

<form onsubmit="return validateForm()"> <input type="text" id="name" placeholder="Name" required> <input type="email" id="email" placeholder="Email" required> <input type="password" id="password" placeholder="Password" required> <button type="submit">Submit</button> </form> <div id="error-message"></div>

JavaScript:

function validateForm() { // Reset error message and remove any highlighting document.getElementById("error-message").textContent = ""; document.querySelectorAll("input").forEach((input) => input.classList.remove("error")); // Get form inputs const name = document.getElementById("name").value.trim(); const email = document.getElementById("email").value.trim(); const password = document.getElementById("password").value.trim(); // Perform form validation checks if (name === "" || email === "" || password === "") { document.getElementById("error-message").textContent = "Please fill out all fields."; return false; // Prevent form submission } // More validations can be added here, such as email format, password strength, etc. return true; // Allow form submission }

In this example, the form will not be submitted if any of the required fields are empty. The error message will be displayed in the error-message element, and the invalid fields will be highlighted by applying the error class. If all the validation checks pass, the form submission will proceed.