CodexBloom - Programming Q&A Platform

HTML <form> Validation Not Triggering on Input Change - implementing Custom Validation Logic

👀 Views: 93 💬 Answers: 1 📅 Created: 2025-06-10
html javascript validation JavaScript

I've spent hours debugging this and I have a form that includes various input fields, and I am trying to implement custom validation logic that should trigger when any input is changed... However, the validation function is not being called when the inputs are modified. I'm using HTML5 and vanilla JavaScript, and here's a simplified version of what I have: ```html <form id="myForm"> <input type="text" id="username" required placeholder="Username"> <input type="email" id="email" required placeholder="Email"> <input type="submit" value="Submit"> </form> ``` ```javascript const form = document.getElementById('myForm'); form.addEventListener('input', function(event) { validateInput(event.target); }); function validateInput(input) { if (input.validity.valid) { console.log(input.id + ' is valid.'); } else { console.behavior(input.id + ' is invalid: ' + input.validationMessage); } } ``` When I change the input fields, I expect the validation messages to be logged in the console, but nothing appears. I’ve checked that the event listener is set correctly, and I’ve confirmed that the fields are required. Still, the `validateInput` function doesn’t seem to be firing as expected. I even tried adding a `change` event listener instead, but that didn’t work either. The inputs are recognized by the browser, as they show the default validation messages when I try to submit the form without filling them. Is there something specific about the event listeners or input types that I might be missing? I'm testing this on Chrome 95, and I’ve ensured that JavaScript is enabled. Any advice would be greatly appreciated! Could someone point me to the right documentation? The stack includes Javascript and several other technologies. I'm developing on CentOS with Javascript. Hoping someone can shed some light on this.