Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
How can I prevent a form from submitting when a required field is empty in JavaScript?
Asked on May 31, 2026
Answer
To prevent a form from submitting when a required field is empty, you can use JavaScript to check the field's value and stop the form submission if it's empty. Here's a simple example using an event listener.
<!-- BEGIN COPY / PASTE -->
<form id="myForm">
<input type="text" id="requiredField" placeholder="Enter something" />
<button type="submit">Submit</button>
</form>
<script>
document.getElementById("myForm").addEventListener("submit", function(event) {
var requiredField = document.getElementById("requiredField").value;
if (requiredField.trim() === "") {
event.preventDefault();
alert("Please fill out the required field.");
}
});
</script>
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- The "submit" event listener is attached to the form element.
- "event.preventDefault()" is used to stop the form from submitting if the required field is empty.
- "trim()" is used to remove any leading or trailing whitespace from the input value.
- An alert is shown to the user if the field is empty, prompting them to fill it out.
Recommended Links:
