Emmanuel Akinfulubi

JavaScriptEvents

Show an error for an empty required field in JavaScript

Intermediate · 4 min read

Every sign-up, checkout and contact form has fields you can't skip. If someone presses Submit with their name missing, the form should stay put, say what's wrong next to the field, and take them straight to it. Doing that well is a small amount of code, but each part exists for a reason.

In this tutorial you will stop a form from submitting when a required field is empty, show an error under each empty field, mark the fields so screen readers announce the problem, and move the cursor to the first one that needs fixing. You should know how addEventListener works and what a for...of loop does.

The page

index.html

<form id="form" novalidate>
  <label for="name">Full name</label>
  <input id="name" name="name" aria-describedby="name-error" required>
  <span id="name-error" role="alert"></span>
  <label for="phone">Phone</label>
  <input id="phone" name="phone" aria-describedby="phone-error" required>
  <span id="phone-error" role="alert"></span>
  <button type="submit">Submit</button>
</form>

Each input has an empty span beside it for its error message. Browsers have their own pop-up messages for required fields. novalidate on the form turns those off, so your code owns the messages. The built-in ones are free and translated for you, but you can't style them or choose their words, so this is a real trade-off.

Three attributes that connect a message to its field

  • aria-invalid="true" on an input tells a screen reader (software that reads the page aloud) that the field has a problem.
  • aria-describedby="name-error" points the input at the span with that id. When the field gets focus, the screen reader reads the message too, so the user hears why it's invalid.
  • role="alert" on the span makes a screen reader announce its text as soon as it changes.

Here is the exercise. Try it on your own first, or read on and we will build it together.

4 Show an error when a required field is empty

fair

On submit, show an error message if a required field was left empty, and do not let the form go through.

Stuck? Three hints, smallest first
  1. 1. A field of only spaces is empty for this purpose, so trim() before testing.
  2. 2. aria-invalid and aria-describedby are what connect the message to the field.
  3. 3. Move focus to the first bad field, or a keyboard user has to hunt for it.

Step 1: stop the form going through

When a form is submitted, the browser sends its data and loads a new page. That built-in reaction is called the default action, and event.preventDefault() cancels it.

Step 1

const form = document.getElementById('form');
form.addEventListener('submit', (event) => {
  event.preventDefault();
});
const event = new Event('submit', { cancelable: true });
form.dispatchEvent(event);
console.log(event.defaultPrevented); // true

defaultPrevented confirms the cancel worked. The cancelable: true is only needed because we are sending the event from code: a real submit is always cancelable.

Step 2: decide what "empty" means

The obvious test is input.value === ''. Now think about a field holding three spaces:

Step 2

console.log('   ' === '');        // false
console.log('   '.trim() === ''); // true

To a person, a field of spaces is empty. To === '', it isn't. trim() removes spaces from both ends of a string, so trim first, then compare.

Step 3: check every field

Put the fields in an array, each with its input, its error span and a label for the message. Then loop over them in the submit handler.

Step 3

const form = document.getElementById('form');
const fields = [
  { input: document.getElementById('name'), error: document.getElementById('name-error'), label: 'Full name' },
  { input: document.getElementById('phone'), error: document.getElementById('phone-error'), label: 'Phone' },
];
let submitted = false;
form.addEventListener('submit', (event) => {
  event.preventDefault();
  let firstBad = null;
  for (const { input, error, label } of fields) {
    const empty = input.value.trim() === '';
    input.setAttribute('aria-invalid', String(empty));
    error.textContent = empty ? `${label} is required.` : '';
    if (empty && !firstBad) firstBad = input;
  }
  if (firstBad) { firstBad.focus(); submitted = false; return; }
  submitted = true;
});
form.dispatchEvent(new Event('submit', { cancelable: true }));
console.log(fields[0].error.textContent); // Full name is required.
console.log(document.activeElement.id); // name

A few things happen for each field:

  • aria-invalid is set to 'true' or 'false' every time, so a field that has been fixed loses its mark.
  • The message is set when the field is empty and cleared when it isn't. Clearing matters: otherwise an old error stays on screen after the user fixes it.
  • firstBad remembers the first empty field. firstBad.focus() moves the cursor there, so a keyboard user doesn't have to hunt for it. document.activeElement is whichever element has focus.

preventDefault() comes first in the handler, before any other work. If something later threw an error, the form still wouldn't slip through.

Step 4: fix the fields one at a time

Step 4

fields[0].input.value = 'Ada Obi';
fields[1].input.value = '   ';
form.dispatchEvent(new Event('submit', { cancelable: true }));
console.log(fields[0].error.textContent === ''); // true: the name error is gone
console.log(fields[1].error.textContent); // Phone is required.
fields[1].input.value = '0801 234 5678';
form.dispatchEvent(new Event('submit', { cancelable: true }));
console.log(submitted); // true

The phone field full of spaces still counts as empty, thanks to trim(). Once both have real values, submitted becomes true. In a real app, that is where you would send the data.

Step 5: style from the same attribute

Instead of adding a separate "error" class, color the border from aria-invalid itself:

CSS

input[aria-invalid="true"] {
  border: 2px solid #a3341f;
}

The red border and what the screen reader announces now come from one attribute, so they can't disagree.

The full solution

The full solution builds the form and runs it through four submits: both empty, name filled, phone of spaces, both filled. Its checks confirm the errors appear and clear, aria-invalid follows, focus moves to the first bad field, a field of spaces still counts as empty, and each message is linked to its field. Press Run, then try the live demo with your keyboard.

Live, in a real browser. Click it. Sandboxed to allow-scripts only, so it cannot reach this page.

The answer

const nameInput = el('input', { id: 'name', name: 'name', 'aria-describedby': 'name-error', required: '' });
const nameError = el('span', { id: 'name-error', role: 'alert' });
const phoneInput = el('input', { id: 'phone', name: 'phone', 'aria-describedby': 'phone-error', required: '' });
const phoneError = el('span', { id: 'phone-error', role: 'alert' });
const form = el('form', { id: 'form', novalidate: '' }, [
  el('label', { for: 'name' }, 'Full name'), nameInput, nameError,
  el('label', { for: 'phone' }, 'Phone'), phoneInput, phoneError,
  el('button', { type: 'submit' }, 'Submit'),
]);
document.body.appendChild(form);

const fields = [
  { input: nameInput, error: nameError, label: 'Full name' },
  { input: phoneInput, error: phoneError, label: 'Phone' },
];

let submitted = false;
let focused = null;

form.addEventListener('submit', (event) => {
  event.preventDefault();                     // never let it through unvalidated
  let firstBad = null;

  for (const { input, error, label } of fields) {
    // trim(), because a field holding only spaces is empty to a reader.
    const empty = input.value.trim() === '';
    input.setAttribute('aria-invalid', String(empty));
    error.textContent = empty ? `${label} is required.` : '';
    if (empty && !firstBad) firstBad = input;
  }

  if (firstBad) { focused = firstBad.id; submitted = false; return; }
  submitted = true;
});

const errors = () => fields.map((f) => f.error.textContent).filter(Boolean);
const invalid = () => fields.filter((f) => f.input.getAttribute('aria-invalid') === 'true').length;

fire(form, 'submit');
console.log('both empty      :', errors(), '| invalid:', invalid(), '| focus moved to', focused);

nameInput.value = 'Ada Obi';
fire(form, 'submit');
console.log('name filled     :', errors(), '| focus moved to', focused);

phoneInput.value = '   ';                     // spaces only
fire(form, 'submit');
console.log('phone is spaces :', errors(), '<- still counted as empty');

phoneInput.value = '0801 234 5678';
fire(form, 'submit');
console.log('both filled     : submitted?', submitted, '| errors:', errors());

Output


      
14 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 14 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

14 checks

test('an empty form produces two errors', (() => { nameInput.value = ''; phoneInput.value = ''; fire(form, 'submit'); return errors().length; })(), 2);
test('and it does not submit', submitted, false);
test('the message names the field', errors()[0], 'Full name is required.');
test('both fields are marked invalid', invalid(), 2);
test('focus went to the first bad field', focused, 'name');
test('filling one clears its error', (() => { nameInput.value = 'Ada Obi'; fire(form, 'submit'); return errors(); })(), ['Phone is required.']);
test('and clears its aria-invalid', nameInput.getAttribute('aria-invalid'), 'false');
test('focus moves to the remaining bad field', focused, 'phone');
test('a field of only spaces still counts as empty', (() => { phoneInput.value = '   '; fire(form, 'submit'); return errors().length; })(), 1);
test('filling both submits', (() => { phoneInput.value = '0801 234 5678'; fire(form, 'submit'); return submitted; })(), true);
test('and every error is cleared', errors(), []);
test('nothing is left marked invalid', invalid(), 0);
test('the error message is linked to its field', nameInput.getAttribute('aria-describedby'), nameError.id);
test('and announced as it appears', nameError.getAttribute('role'), 'alert');

Three things make the difference between an error message and a usable one. trim(), because a field holding spaces is empty to a person and non-empty to === ''. aria-describedby pointing at the message element, so a screen reader reads the reason when focus reaches the field rather than announcing an unexplained "invalid". And moving focus to the first bad field, since a keyboard user otherwise has to tab around looking for it.

aria-invalid does double duty: it is what gets announced, and styling from input[aria-invalid="true"] rather than a separate class means the red border and the announced state come from the same attribute and cannot disagree.

novalidate on the form turns off the browser's own bubbles so this code owns the messages. That is a real choice: the native ones are free and localised, but you cannot style them or control their wording.

Common mistakes

  • Not trimming. A field of spaces passes value === '' and gets submitted. Use value.trim() === ''.
  • Leaving old errors behind. If you only ever set the message, it stays after the field is fixed. Set it to '' when the field is fine.
  • Showing the error without linking it. Without aria-describedby, a screen reader may say "invalid" with no reason. Point the input at its message.

Try it yourself

  1. Also check each field when the user leaves it, using the blur event, so errors show up before Submit.
  2. Add an email field and also refuse a value that has no @ in it.
  3. Show a summary line above the form, such as "2 fields missing", and update it on every submit.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.