JavaScript
Beginner
Forms
· 1 min read
Block empty form fields in JS
How do I stop submit when a field is blank?
preventDefault + trim check.
Example
Interactive preview availabledocument.querySelector('#signup')?.addEventListener('submit', (e) => {
const name = document.querySelector('#name');
if (! name.value.trim()) {
e.preventDefault();
alert('Name is required');
}
});
Line-by-Line Walkthrough
Still validate again on the server in PHP.