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 field is empty?
Asked on Mar 02, 2026
Answer
To prevent a form from submitting when a field is empty, you can use JavaScript to check the field's value and stop the submission if it's empty.
<!-- BEGIN COPY / PASTE -->
<form id="myForm">
<input type="text" id="myField" placeholder="Enter text">
<button type="submit">Submit</button>
</form>
<script>
document.getElementById('myForm').addEventListener('submit', function(event) {
const field = document.getElementById('myField');
if (field.value.trim() === '') {
event.preventDefault(); // Prevent form submission
alert('Field cannot be empty!');
}
});
</script>
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- The "submit" event listener is attached to the form element.
- "event.preventDefault()" stops the form from submitting if the field is empty.
- "field.value.trim()" is used to check if the field is empty after removing any leading or trailing whitespace.
Recommended Links:
