JavaScript Beginner Forms · 1 min read

Block empty form fields in JS

Start the JavaScript learning path »

❮ JavaScript Home All Tutorials ❯

How do I stop submit when a field is blank?

preventDefault + trim check.

Example

Interactive preview available
JavaScript Example
document.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.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…