CodexBloom - Programming Q&A Platform

HTML Form Validation Not Triggering on Custom Submit Button - Issues with Prevent Default

šŸ‘€ Views: 37 šŸ’¬ Answers: 1 šŸ“… Created: 2025-06-09
html javascript form-validation JavaScript

I'm integrating two systems and I've tried everything I can think of but Quick question that's been bugging me - I've been struggling with this for a few days now and could really use some help..... I'm having trouble with HTML form validation not triggering when I use a custom button for submission instead of the default form submit button. I've created a form with several required fields, but when I click my custom button, the validation doesn't seem to run. The button has an `onclick` event that calls a function which uses `event.preventDefault()` to stop the default action, but I'm not sure how to correctly handle form validation afterward. Here's a simplified version of my HTML form: ```html <form id="myForm"> <input type="text" name="username" required placeholder="Username" /> <input type="email" name="email" required placeholder="Email" /> <button id="customSubmit">Submit</button> </form> ``` And my JavaScript looks like this: ```javascript document.getElementById('customSubmit').onclick = function(event) { event.preventDefault(); // Prevents the form from submitting if (document.getElementById('myForm').checkValidity()) { // This part never runs alert('Form is valid!'); // Here I would normally submit the form, but I want to validate first. } else { alert('Please fill out all required fields.'); } }; ``` When I click the custom button, I see the alert for invalid forms, but the validation doesn't function properly for valid forms. I'm also considering using `form.reportValidity()`, but I’m not sure how that integrates with my current setup. Any guidance on how to properly implement validation with a custom submit button would be greatly appreciated, especially how to handle the submit action correctly if validation passes. I'm working on a CLI tool that needs to handle this. For context: I'm using Javascript on Windows. Has anyone else encountered this? This issue appeared after updating to Javascript 3.10. Has anyone dealt with something similar? What's the best practice here? I'm working on a desktop app that needs to handle this. I'd be grateful for any help.