Web Development

HTML Forms and Validation: Labels, Inputs and Error Messages

Flat illustration of a form with labelled fields and a submit button

A form collects information from a reader and sends it somewhere for processing. The form element wraps the fields, a submit button sends the data, and each field holds one piece of information, such as a name, an email address or a message. Validation is the set of checks that decide whether that information is acceptable before it is sent. Some checks run in the browser, using attributes in the HTML itself, and some checks must run on the server, where the data is received. Both kinds matter, and they serve different purposes.

This guide builds a contact form step by step. You will learn how labels connect to fields, which input types to choose, how built-in browser checks work, and how to write error messages that help a reader fix a problem instead of guessing at it. The examples build on the page structure in the guide to HTML basics for beginners, and the handling of a submitted form in JavaScript is covered in the guide to JavaScript events, clicks and inputs.

Labels and inputs

A label is a short description of a field, and it does more than show text beside an input. When a label is linked to a field, clicking the label focuses that field, and a screen reader announces the label when the field receives focus. That link is made with the for attribute on the label and the id attribute on the field, and the two values must match exactly, including case. A field without a label, or with a label that is only placeholder text inside the field, is harder to use, because the placeholder disappears as soon as typing starts and it is not announced in the same way as a label.

<form action="/contact" method="post">
  <label for="name">Your name</label>
  <input id="name" name="name" type="text" required>

  <label for="email">Email address</label>
  <input id="email" name="email" type="email" required>

  <button type="submit">Send message</button>
</form>

The name attribute decides what the field is called when the data is sent. A field without a name is not included in the submitted data, even if the reader filled it in. The id attribute is for the page itself, for labels and for JavaScript, while the name attribute is for the submitted data. Keeping those two roles separate prevents a common confusion, where a field works on screen but its value never reaches the server. The action attribute on the form says where the data goes, and the method attribute says how it is sent, with post being the usual choice for a message that changes something on the server.

Choosing the right field type

The type attribute on an input tells the browser what kind of data the field holds, and the browser changes its behaviour accordingly. A text field accepts any text, while an email field checks that the value looks like an email address and shows a suitable keyboard on a phone. A number field accepts numbers and can show up and down controls, while a date field shows a date picker. A password field hides the characters as they are typed, and a checkbox or radio button offers a choice rather than free text. Choosing the right type gives the reader free help from the browser, without any extra code.

DataType to useBrowser help you get
Ordinary texttextPlain entry, no format check
Email addressemailFormat check, email keyboard on phones
Number or quantitynumberNumeric entry, optional minimum and maximum
DatedateDate picker, consistent date format
Longer messagetextarea elementMulti-line entry, resizable by the reader

Built-in validation and error messages

Built-in validation uses attributes on the field itself. The required attribute means the field must have a value before the form can be submitted. The minlength and maxlength attributes set limits on text length, and min and max set limits on a number or a date. The pattern attribute holds a regular expression that the value must match, which suits a code or a reference number with a fixed format. When a field fails one of those checks, the browser blocks submission and shows a message near the field. That message is a starting point, and for a public form it is worth checking what the message says in the browsers your readers use, because the wording varies.

<label for="postcode">Postcode</label>
<input id="postcode" name="postcode" type="text"
  minlength="5" maxlength="8" required>

A good error message says what is wrong and how to fix it. A message that only says invalid input leaves the reader guessing, while a message that says the postcode must be between 5 and 8 characters gives a clear next step. Error text should sit close to the field it describes, and it should be linked to the field so that a screen reader announces it when the field receives focus. Colour alone is not enough to mark an error, because a reader who cannot distinguish the colour will miss it, so an icon or a text prefix helps as well. The guide to semantic HTML tags and accessibility covers related points about structure and assistive technology.

Common mistakes

The first mistake is a label that does not match its field. A for value that differs from the id by one character, or an id used twice on the same page, breaks the link, and clicking the label focuses nothing or focuses the wrong field. Unique ids and a careful check of the for values prevent that problem. A second mistake is relying on placeholder text as the only label, which disappears on typing and gives a screen reader less to work with. Placeholder text is useful as an example of the expected format, and it works best alongside a real label.

A third mistake is marking every field as required, even fields that are genuinely optional. Readers then face a blocked form for information they do not need to give, and some will abandon the form rather than invent a value. Marking optional fields clearly, and requiring only what the form truly needs, improves completion and gives cleaner data. A related mistake is a pattern that is stricter than the real data, such as a postcode pattern that rejects a valid format. Testing a pattern with real examples, including edge cases, catches that problem before readers meet it.

Where forms do not apply

A form is not the right tool for navigation or for a simple action that needs no data. A link takes a reader to another page, and a button that only changes something on the current page belongs to JavaScript, not to a form submission. Using a form for those jobs adds a page reload and a submission step that the reader did not expect. Forms are for collecting data and sending it somewhere, and that scope keeps their behaviour predictable.

Worked example: a signup form with labels and hints

A signup form shows how labels, inputs, hints and errors fit together. Each field gets a label element linked to its input by matching the label for attribute to the input id. A short hint under a field explains the format expected, such as a password length, and the hint is linked to the input with aria-describedby so assistive technology announces it together with the field. The submit button sits at the end, clearly labelled with what it does.

<form action="/signup" method="post">
  <label for="email">Email address</label>
  <input id="email" name="email" type="email" required
         aria-describedby="email-hint">
  <p id="email-hint">We will only use this to contact you.</p>
  <button type="submit">Create account</button>
</form>

The required attribute tells the browser the field must be filled before the form can be submitted, and the email type tells it to check that the value looks like an email address. Those two attributes give you working validation with no JavaScript at all, and the browser shows its own error message near the field when the check fails. That built-in behaviour is a strong starting point, and custom validation should build on it rather than replace it without a reason.

Group related fields with fieldset and legend when a form has distinct sections, such as contact details and delivery details. The legend acts as a heading for the group, and assistive technology announces it when the reader enters the group, which gives the fields context that a visual heading alone would not provide.

Built-in validation attributes and when to use them

HTML offers a set of validation attributes that cover most common cases without any script. Minlength and maxlength bound the length of a text value. Min and max bound a number or a date. Pattern accepts a regular expression for formats such as a postcode, though the pattern should be kept simple and explained in the hint text, because a pattern the reader cannot understand produces errors they cannot fix.

AttributeUse it for
requiredA field that must be filled before submission.
type="email"An email address, checked for a basic email shape.
minlength / maxlengthA minimum or maximum length for text.
min / maxA range for a number, date or time value.
patternA specific format, explained in nearby hint text.

Built-in validation has limits that are worth knowing. The email type checks the shape of the address, not whether the address exists or belongs to the reader. A pattern can reject a valid value if it was written too narrowly, which is why patterns need testing with real examples, including edge cases such as names with hyphens or apostrophes. When a rule depends on another field, such as two password fields matching, JavaScript is needed, because HTML attributes cannot compare two fields.

Error messages readers can actually act on

An error message should say which field has the problem, what is wrong, and how to fix it. "Invalid input" fails all three tests. "Enter an email address, such as name@example.com" passes them, because it names the field type, states the problem, and shows a correct example. Place the message near the field it refers to, and link it to the field so assistive technology announces the two together, in the same way a hint is linked.

Timing matters as much as wording. Showing an error while the reader is still typing the first character is irritating, because the field is incomplete by definition at that point. A better moment is when the reader leaves the field, or when the form is submitted. On submission, move focus to the first field with an error, or to a summary of errors at the top of the form that links to each problem field, so a keyboard user does not have to hunt through the form to find what went wrong.

Keep error styling separate from colour alone. A red border helps sighted readers, but a reader who cannot distinguish the colour needs the message text as well, and an icon can reinforce it. The accessibility guide on this site covers colour and meaning in more detail, and the same principle applies here: never let colour be the only signal that something is wrong.

Validation beyond the browser: what to check on the server

Browser validation improves the experience for honest readers, but it is not a security boundary. A reader can turn JavaScript off, edit the page in developer tools, or submit a request directly, bypassing every browser check. Server-side validation is therefore required for any form that matters, and it should repeat every rule the browser enforced, plus any rule the browser cannot check, such as whether an email address is already registered.

That division of labour keeps each side honest. The browser gives fast feedback and a smooth experience. The server protects the data and enforces the rules no matter how the request arrives. A form that relies only on browser validation will eventually accept bad data, and a form that relies only on server validation will feel slow and unhelpful, because every mistake needs a round trip to be discovered.

When a server check fails, return the reader to the form with their entries preserved and the errors explained beside the relevant fields. Forcing a reader to retype a whole form because of one bad field is one of the fastest ways to lose a submission, and it is entirely avoidable with a little care in how the error page is built.

Test a form with real entries before publishing

A form that looks complete in code can still fail with real entries, because test data is usually tidy while reader entries are not. Before publishing, fill the form with realistic values: a name with a hyphen, an email address with a subdomain, a long address, and a password that meets the stated rules. Submit each version and confirm the form accepts what it should accept and rejects what it should reject, with a message that explains the rejection.

Also test the unhappy paths that readers meet most often. Leave a required field empty, enter a plain word where an email address is expected, and enter a value that is too short for a field with a minimum length. Each of those should produce a clear message beside the right field, not a generic failure at the top of the page. A form that passes its happy path but confuses readers on its unhappy paths will still lose submissions, because real readers make exactly those mistakes.

Frequently asked questions

Do I still need server validation if the browser checks the form?

Yes. Browser checks help the person filling in the form, but they can be bypassed, so any data that matters must be checked again on the server before it is used or stored.

Why does clicking a label focus the wrong field?

That usually means the label for attribute does not match the field id, or two fields share the same id. Give each field a unique id, and set the label for value to that exact id.

What input type should I use for an email address?

Use type email. The browser then checks that the value looks like an email address, and a phone keyboard often shows the at sign and other email characters, which makes entry easier.

Can I rely on browser validation alone?

No. Browser validation gives fast feedback, but it can be bypassed, so the server must repeat every important check. Treat browser validation as a convenience for readers and server validation as the real boundary.

Why is placeholder text not a substitute for a label?

Placeholder text disappears when the reader starts typing, and it is not announced as reliably as a label. A visible label stays beside the field, and a label element linked to the input is announced together with it by assistive technology.

Sources