To validate a form using JavaScript and prevent submission on error, you can follow these steps:
onsubmit
attribute to the HTML form element.event.preventDefault()
method to prevent form submission if there are any errors.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.