Skip to content
Tutorials Center
My learning

Topics

Lesson 117 of 122 Β· Projects

Project: Accessible Contact Form

Build an accessible contact form step by step with labels, fieldsets, hints, validation and clear error messages, plus a submit handler that shows the data.

Almost every website has a contact form, and a surprising number of them are hard to use. Labels vanish when you start typing, errors appear only as a red border, the keyboard gets lost, and screen readers announce "edit text, blank" for every field. In this project you will build a contact form that avoids all of that and works well for everyone: mouse, touch, keyboard and screen-reader users alike.

You will put together everything from the Forms chapter: labels and fieldsets, the right input types, radio buttons, a drop-down, validation, and a little JavaScript. Because the editors on this site must never send data to a real server, the form's submit handler will show you exactly what would be sent.

Step 1: Labeled fields

Start with the three fields every contact form needs: name, email and message. Each one gets a visible <label> connected to its control with for and id. That connection gives the field an accessible name and makes the label clickable, which is a bigger target on touch screens.

Step 1: labeled fields

Three details already help a lot:

  • Visible labels, not placeholders. Placeholder text disappears as soon as you type, has poor contrast and isn't a reliable accessible name. A real label is always there.
  • type="email" shows an email keyboard on phones and lets the browser check the format.
  • autocomplete tokens such as name and email let browsers fill in the fields, a huge time saver for everyone and especially for people with motor or memory difficulties. See Input Attributes for the full list.

Step 2: Grouping with fieldsets, hints and choices

Next, add a topic drop-down, a choice of how to be contacted, and an optional phone number. Related radio buttons must be grouped in a <fieldset> with a <legend>: screen readers announce the legend ("How should we reply?") before each option, so "Email" and "Phone" make sense on their own.

A hint tells people what you expect before they make a mistake. Connect it to its field with aria-describedby, so screen readers read it after the label.

Step 2: fieldset, hints and choices

Here the radio labels wrap their inputs instead of using for. Both ways work; wrapping is convenient for short labels that sit next to their control.

type="tel" shows a phone keypad on mobile devices. It doesn't check the format, because phone numbers vary so much between countries. You will add a gentle check with pattern in the next step.

Step 3: Validation rules

HTML can enforce most rules without any JavaScript. Add these attributes:

Field Rules
Name required
Email required, and type="email" checks the format
Topic required; the first option has value="", so it counts as "nothing chosen"
Phone pattern="[0-9 +\(\)\-]{6,}": at least six characters, using only digits, spaces and + ( ) -
Message required, minlength="20", maxlength="1000"
Consent A required checkbox

Inside a pattern, the brackets and the hyphen are written as \(, \) and \-. Browsers compile patterns in a strict regular-expression mode in which these characters must be escaped inside [...]; an invalid pattern is silently ignored.

Mark required fields in the label text, so the requirement is visible to everyone and read out by screen readers. A word such as "(required)" is clearer than a lone asterisk.

Step 3: built-in validation

Press Send message with empty fields. The browser stops the submission and shows its own message bubble on the first problem. The :user-invalid selector paints a red border, but only after the user has interacted with a field, so the form doesn't greet visitors with a wall of red.

Built-in validation is a good start, but it has weaknesses. The bubbles disappear after a few seconds, look different in every browser, show only one problem at a time, and their wording can't be fully controlled. The final step replaces them with messages written into the page.

Browser validation is a convenience, not security. Anyone can switch it off or send data directly to your server. The server must always check every field again.

Step 4: Clear error messages and a submit handler

Accessible error messages follow a few rules:

  1. Write them into the page next to the field, in text, not only as a color.
  2. Connect them to the field with aria-describedby, and set aria-invalid="true", so screen readers announce "invalid entry" and read the message.
  3. Say how to fix it: "Enter an email address like [email protected]" beats "Invalid input".
  4. Move focus to the first problem after a failed submit, so keyboard and screen-reader users land right where they need to be.

The plan for the script:

  • Add novalidate to the form. This switches off the browser's bubbles, but the browser still checks every field, and the results are available through the constraint validation API (field.validity and form.checkValidity()).
  • On submit, check each field and write a message into its error element.
  • When everything is valid, collect the values with FormData and show them on the page instead of sending them.

The full code is in the final step below. Here is the core of it, so you can read it on its own:

JavaScript
function messageFor(field) {
  const v = field.validity;
  if (v.valueMissing) return field.dataset.missing || 'Please fill in this field.';
  if (v.typeMismatch) return 'Enter an email address like [email protected].';
  if (v.tooShort) return `Please write at least ${field.minLength} characters (you have ${field.value.length}).`;
  if (v.patternMismatch) return field.dataset.pattern || 'Please check the format.';
  return field.validationMessage;
}

Each field can carry its own wording in a data-* attribute, such as data-missing="Please tell us your name."; you met these in Custom Data Attributes.

Step 5: The complete form

Here is the finished, polished form. Try these things:

  • Press Send message straight away. Every problem gets a message, and focus jumps to the first one.
  • Fix a field. Its message disappears as soon as the value becomes valid.
  • Choose Phone as the reply method. The phone field becomes required.
  • Fill everything in correctly and send. The data that would be submitted appears below the form.
  • Do it all with the keyboard only: Tab, arrow keys for the radio buttons, Space for the checkbox and Enter to send.
Step 5: complete contact form

Some choices in this code are worth calling out:

  • Errors are text inside the page. Each .error paragraph is empty (and hidden by :empty) until there is a problem. Because the field's aria-describedby already points to it, screen readers read the message whenever the field gets focus.
  • aria-invalid="true" is set only on fields that fail, and removed when they pass. The CSS uses the same attribute for the red border, so the visual and the accessible state can never disagree.
  • Focus moves on purpose. After a failed submit it goes to the first invalid field; after success it goes to the "Thank you!" heading (which has tabindex="-1" so it can receive focus from a script without becoming a Tab stop). See Keyboard Access and Focus.
  • User text is inserted with textContent, never innerHTML, so a message containing <script> is shown as text, not run.
  • The submit button is a real <button> inside the form, so pressing Enter in a field submits, exactly as people expect. See Text Areas and Buttons.

Connecting it to a real server

To make the form send for real, remove the preventDefault() call and give the form an action and method, as covered in Form Attributes:

HTML
<form id="contact" action="/contact" method="post" novalidate>

Keep the JavaScript checks: when the form is valid, simply don't call preventDefault(), and the browser submits it. Your server must then validate every field again, send a confirmation, and show a success page, ideally one with a clear heading such as "Thank you, we received your message".

Check your understanding

Quick check Β· 4 questions

of 4 answered You scored / 4 Β· perfect!

  1. 1. Why use a visible <label> instead of placeholder text?

    A label stays visible, can be clicked to focus the field and is announced by screen readers. Placeholder text vanishes and often has poor contrast.
  2. 2. What does adding novalidate to the form do in this project?

    With novalidate the form submits without the built-in bubbles, but validity and checkValidity() still report problems, so your script can show its own messages.
  3. 3. How does a screen reader learn about the error message under a field?

    aria-describedby links the message to the field, and aria-invalid announces that the value is invalid. Color alone is invisible to many users.
  4. 4. Why must the server validate the data again?

    Client-side checks help honest users. Anyone can disable them or send a request directly, so the server must always check.

Summary

  • Give every field a visible <label> linked with for/id, the right type and an autocomplete token.
  • Group radio buttons in a <fieldset> with a <legend>; connect hints with aria-describedby.
  • Use HTML constraints (required, type, minlength, maxlength, pattern) and say "(required)" in the label.
  • With novalidate, read field.validity and write clear, specific messages into the page; set aria-invalid and focus the first problem.
  • Collect values with FormData, insert user text with textContent, and always validate again on the server.

Next lesson: Project: Responsive Landing Page, the final project, where you build a complete marketing page that adapts to every screen.