CodeBlanks Logo Icon CodeBlanks

Challenge - Form and storage

JavaScript course · Intermediate · Lesson 132/134

Build a contact form with form validation, localStorage and JSON.

Contact form handler

In this challenge you will build a contact form. When the form is submitted you call preventDefault to stop the page reload, read the fields and validate them.

Validation is simple: if the name or message is empty you show an error. If valid, the name is stored in the browser with localStorage.setItem and survives a reload.

The storage key is a string and so is the value. For simple data setItem is enough.

Read and validate values

To access form fields you use the .value property. If the name or message is an empty string validation fails and you write a message to the error element.

If validation passes you store the name with localStorage.setItem('contactName', name). You also clear the error element so the old message does not stay.

Tip: setItem converts any value to a string. That makes it ideal for simple text.

Exercise Write the handleSubmit function

Write the handleSubmit(event) function. First call event.preventDefault(). Read the name and message with nameInput.value and messageInput.value. If either is an empty string, write an error to errorEl.textContent and return. If both are filled, store the name with localStorage.setItem('contactName', name) and set errorEl.textContent to an empty string.

Show example solution
Open function handleSubmit(event). Call event.preventDefault(). Read nameInput.value and messageInput.value. If either is empty, set errorEl.textContent = '...' and return. Otherwise call localStorage.setItem('contactName', name) and set errorEl.textContent = ''.

Example solution:
function handleSubmit(event) {
  event.preventDefault();
  const name = nameInput.value;
  const message = messageInput.value;
  if (name === '' || message === '') {
    errorEl.textContent = 'Please fill in all fields';
    return;
  }
  localStorage.setItem('contactName', name);
  errorEl.textContent = '';
}

Test yourself

  1. What is the first step to handle a form submit with JS?

    • Remove the form from HTML
    • Call preventDefault on the submit event
    • Reload the page
    • Hide the inputs
    Show answer

    Call preventDefault on the submit event — Correct. preventDefault stops the default page reload and gives JS control.

  2. Save the name to local storage

    function handleSubmit(event) {
      event.preventDefault();
      const name = nameInput.value;
      localStorage.____;
      errorEl.textContent = '';
    }
    Show answer
    function handleSubmit(event) {
      event.preventDefault();
      const name = nameInput.value;
      localStorage.setItem('contactName', name);
      errorEl.textContent = '';
    }

All lessons in Intermediate