I am using the javaScript Constraint Validation API to validate a form. It’s a book form with 3 inputs: title, author, and pages. I was trying to stop the form from submitting when constraints are not met but it keeps submitting.
I experimented around for a bit and found out it was the form.addEventListener not listening. I know a common mistake is people misplacing the event listener on the submit button, but I am placing the event listener on the form but it’s still not working.
I tried logging to the console when the form submits but nothing happens, so I’m thinking it’s not detecting the submit event but I don’t know why.
I checked for typos and read through tons of mdn and w3school docs and I still can’t find why, please help 🙁
The html code:
<form id="form">
<h2>Add Book Info</h2>
<input type="text" id="title" placeholder="Book Title" name="title" required>
<span class="error"></span>
<input type="text" id="author" placeholder="Author" name="author" required>
<span class="error"></span>
<input type="number" id="pages" placeholder="Page Count" name="pages" required>
<span class="error"></span>
<div class="check">
<input type="checkbox" id="read">
<label for="read">Have you read the book?</label>
</div>
<button type="submit" id="submitBtn">Submit</button>
<button type="button" id="closeBtn">Cancel</button>
</form>
The js code:
// validating form
const title = document.getElementById("title");
const author = document.getElementById("author");
const pages = document.getElementById("pages");
const err = document.getElementsByClassName("error")
const titleErr = document.querySelector("#title + span.error")
const authorErr = document.querySelector("#author + span.error")
const pagesErr = document.querySelector("#pages + span.error")
const form = document.getElementById("form");
form.addEventListener("submit", (e) => {
console.log("form submitted");
if (!title.checkValidity()) {
e.preventDefault();
error.innerText = "Please enter the title";
console.log("Title not entered");
}
});
Ruby Hu is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.