The Blue Cup's booking form now asks for everything it needs and is well organised, but it accepts anything: it can be submitted without a name, with a date from last year, at three o'clock in the morning, with a three-digit phone number or without accepting the privacy policy. Each of those submissions would force the staff to phone or email the customer to clarify the details, if they even can. Validation means checking that the data meets a set of rules before accepting it. HTML lets you declare many of those rules with simple attributes, and the browser takes care of checking them and warning the user, without JavaScript. In this lesson you will meet those attributes (required, minlength, maxlength, min, max, step, pattern), others that improve the experience of filling in a form (placeholder, autocomplete, autofocus, readonly), how to turn validation off when it makes sense and, above all, a warning you must never forget: browser validation helps, but it does not protect.

Contents

  1. What validation is and where it happens
  2. Required fields: required
  3. Text length: minlength and maxlength
  4. Ranges: min, max and step
  5. Custom formats: pattern
  6. Hint text: placeholder
  7. Autofill: autocomplete
  8. Initial focus: autofocus (with caution)
  9. readonly versus disabled
  10. Turning validation off: novalidate and formnovalidate
  11. The browser's native messages
  12. Styles based on validity (a brief mention)
  13. Client-side validation is no substitute for server-side validation
  14. Project: validating the booking form

What validation is and where it happens

Validating means checking that each data item is acceptable: that it is present if it is required, that it has the correct format and that it is within reasonable limits. It can be done in two places:

Client-side validation (browser) Server-side validation
When Before submitting, when the button is clicked After receiving the data
With what HTML attributes (and, optionally, JavaScript) The server program
What it is for Helping the user: it warns instantly, without waiting Protecting the system and the data
Can it be bypassed? Yes, easily No, if it is properly programmed

This lesson is about the first. You have already seen it in action without looking for it: in HTML5 Input Types, the browser refused to submit an email address without an @ or a number outside min and max. Now you will learn to declare your own rules.

How it works, broadly speaking:

  1. The user clicks the submit button.
  2. The browser checks every rule on every field.
  3. If any of them fails, it cancels the submission, moves the focus to the first invalid field and displays a message next to it.
  4. If they are all met, it submits the form as usual.

Required fields: required

The boolean attribute required makes a field mandatory:

<label for="name">Name</label>
<input type="text" id="name" name="name" required>

What "filled in" means depends on the control:

Control required is met if…
Text input, email, tel, date… and textarea It isn't empty
input type="checkbox" It is ticked
Group of input type="radio" One option is selected in the group (it is enough to put required on one of the buttons, although it is clearer to put it on all of them)
select The chosen option doesn't have an empty value (which is why the first value="" option you saw in Form Elements: input, textarea and select is useful)
input type="file" A file has been chosen

A checkbox with required is the way to make users accept conditions, such as the privacy policy.

Show visually what is required. The browser doesn't do so until the user tries to submit. The most widespread convention is an asterisk in the label and a note at the start of the form:

<p>Fields marked with * are required.</p>
…
<label for="name">Name *</label>
<input type="text" id="name" name="name" required>

Screen readers announce "required" on fields with required, so the asterisk is for those who can see the page. If there are only a few optional fields, the opposite is also valid: mark those with "(optional)", as you already did with the occasion.

Text length: minlength and maxlength

For text fields (text, email, tel, url, search, password) and textarea:

<input type="text" id="name" name="name" required minlength="2" maxlength="60">
<textarea id="comments" name="comments" rows="4" cols="40" maxlength="500"></textarea>
  • minlength: minimum number of characters. If the user types fewer, the browser warns on submission. An empty field doesn't break it: if it must have content, add required.
  • maxlength: maximum number of characters. It works differently: the browser won't let you type any more. If the user pastes a long text, it is cut off.

Use maxlength generously, not as a punishment: 60 characters for a name or 500 for comments are reasonable limits that prevent abuse without bothering anyone. And think about real names: there are very long double-barrelled surnames and two-letter names.

Ranges: min, max and step

You have already used them with number. They work the same way with range, date, time, datetime-local, month and week, always written in the value format (not the on-screen format):

<input type="date" id="date" name="date" min="2026-12-01" max="2027-03-31">
<input type="time" id="time" name="time" min="08:00" max="19:00" step="1800">
<input type="number" id="guests" name="guests" min="1" max="12" step="1">
Type min / max in format step is measured in Example of step
number, range number units 1, 0.5, any
date YYYY-MM-DD days 7 (one week)
time HH:MM seconds 1800 (30 minutes), 900 (15 minutes)
datetime-local YYYY-MM-DDTHH:MM seconds 1800

Remember that step counts from min: with min="08:00" and step="1800", 8:00, 8:30, 9:00… are valid, but 8:15 is not.

Calendars and time pickers usually respect the limits (they disable the days before min), but not always the steps. In any case, if the value entered doesn't comply, the warning will appear on submission.

The minimum date problem

The logical thing would be for min to be today, so as not to allow bookings in the past. But HTML is static: min="2026-12-01" is a fixed date which, in a month's time, will be out of date. Working out "today" automatically requires JavaScript or the server generating the page with the current date. In this course, with neither of those, you will set a fixed date and update it by hand; and, in any case, the server will have to reject past dates (you will see this at the end of the lesson).

Custom formats: pattern

pattern requires the whole value to match a regular expression, a small language for describing text patterns. It works on the text types (text, tel, email, url, search, password).

Regular expressions could fill a whole course; with these pieces you will be able to write the most common patterns:

Piece Meaning Example Matches
[0-9] One character from the range [0-9] 5
[6-9] One character between 6 and 9 [6-9] 7
[A-Z] One capital letter (no accented letters or Ñ) [A-Z] B
{n} Repeats the previous item n times [0-9]{5} 08001
{n,m} Between n and m times [0-9]{2,4} 12, 1234
? The previous item is optional a? a or nothing
( ) Groups (ab)? ab or nothing
\+ A literal + (the backslash removes its special meaning) \+34 +34
space A literal space [0-9] [0-9] 1 2

Two important details:

  • The pattern must be matched in full: the browser compares it with the whole value, from start to finish. [0-9]{5} doesn't accept 080012.
  • An empty field doesn't break pattern. If it is required, add required.

Example 1: Spanish postcode

<label for="postcode">Postcode</label>
<input type="text" id="postcode" name="postcode" inputmode="numeric" pattern="[0-9]{5}">

Exactly five digits. inputmode="numeric" displays the numeric keypad on mobile, as you saw in the previous lesson.

Example 2: The Blue Cup's phone number

You want to accept 9-digit Spanish phone numbers starting with 6, 7, 8 or 9, with or without the +34 prefix, and with or without spaces between the digits, such as 600 000 000, 600000000 or +34 900 000 000:

<input type="tel" id="phone" name="phone" pattern="(\+34 ?)?[6-9]( ?[0-9]){8}">

Read it piece by piece:

Piece Meaning
(\+34 ?)? Optionally, the prefix +34 followed, optionally, by a space
[6-9] The first digit of the number: 6, 7, 8 or 9
( ?[0-9]){8} Eight times: an optional space followed by a digit

It accepts 612345678, 612 345 678, +34612345678 and +34 612 34 56 78. It rejects 12345 (too short), 512345678 (it starts with 5) and 612-345-678 (hyphens are not allowed).

This rule excludes phone numbers from other countries. It is a business decision: The Blue Cup is a neighbourhood café and prefers a clear format. If it had many foreign customers, a more permissive pattern, or none at all, would be better.

Always explain the format

If the user doesn't match the pattern, the browser will display a generic message such as "Please match the requested format.", which explains nothing. To help them:

  • Write the expected format in visible text next to the field.
  • Add the title attribute with the explanation: many browsers include it in the pattern error message (although not all, and not on every device, so the visible text is still necessary).

Hint text: placeholder

In the previous lesson you saw that placeholder is no substitute for a label. Its correct use is to show an example of the expected format:

<label for="phone">Phone *</label>
<input type="tel" id="phone" name="phone" required placeholder="600 000 000">

Guidelines:

  • Make it an example that is clearly fictitious and looks like an example, not something that seems to have been typed already.
  • Don't put important instructions only in the placeholder: they disappear when the user types. The format must also be in visible text.
  • It only works on text fields, number and textarea; on date, time or checkbox it has no effect.

Autofill: autocomplete

Browsers remember the data you type (name, email, phone, address) and offer it in other forms. The autocomplete attribute tells them exactly which data item each field is asking for, so that they get it right:

<input type="text" id="name" name="name" autocomplete="name">
<input type="email" id="email" name="email" autocomplete="email">
<input type="tel" id="phone" name="phone" autocomplete="tel">

The most useful values:

Value Data item
name Full name
given-name / family-name First name / surname separately
email Email address
tel Full phone number, with prefix
street-address Postal address
postal-code Postcode
bday Date of birth
organization Company
off Don't suggest anything (for example, for a one-time code)

Advantages:

  • The user fills in the form in seconds, with a single tap, especially on mobile.
  • Fewer typing errors in the email address or phone number.
  • It is an accessibility guideline: it helps people with motor or memory difficulties.

Note that the value of autocomplete is a standard name for the data item, independent of your name: your field could be called name="phone" and carry autocomplete="tel". You can also put autocomplete on the form to apply it to all its fields, although it is usual to specify it field by field.

Initial focus: autofocus (with caution)

autofocus places the cursor in a field as soon as the page loads:

<input type="search" id="search" name="q" autofocus>

It may seem convenient, but it has drawbacks:

  • Screen reader users land in the middle of the page and skip all the content before it: the logo, the menu, the h1 and the explanations.
  • On mobile, it suddenly opens the keyboard, covering half the screen.
  • The page "jumps" to that field if it is further down.

Only use it when the form is the page and there is nothing important before it, such as the home page of a search engine or a sign-in screen. There can only be one per page. In bookings.html, which starts with explanations, you will not use it.

readonly versus disabled

Both prevent the user from changing a field, but they are not equivalent:

<input type="text" id="premises" name="premises" value="12 Example Street" readonly>
<input type="text" id="coupon" name="coupon" value="AUTUMN26" disabled>
readonly disabled
Can it be edited? No No
Does it receive focus? Can it be selected and copied? Yes No
Appearance Normal (sometimes subtly different) Greyed out
Is it sent? Yes No
Is it validated? No No
What the screen reader announces "Read only" "Unavailable"
Works on Text fields, dates, numbers, textarea All controls (and fieldset)

Use them like this:

  • readonly: the data item is part of the submission but must not be changed here (for example, a booking code that the user needs to see and send).
  • disabled: the control doesn't apply at the moment (for example, the fully booked workshop from the previous lesson).

And the usual warning: neither readonly nor disabled protects anything. With DevTools they can be removed in a second.

Turning validation off: novalidate and formnovalidate

Sometimes you want to submit without validating:

<!-- Turns off validation for the whole form -->
<form action="…" method="post" novalidate>

<!-- Turns off validation only when this button is clicked -->
<button type="submit">Send booking</button>
<button type="submit" name="action" value="draft" formnovalidate>Save draft</button>
  • novalidate on the form: the browser checks nothing on submission. It is used when validation is done entirely with JavaScript, with custom messages.
  • formnovalidate on a submit button: that particular button submits without validating. Useful for "Save draft", where it is normal for data to be missing.

It is also a testing tool: add novalidate temporarily to check what the server would do with incorrect data.

The browser's native messages

When a field is invalid, the browser displays a message in a bubble next to the field:

Rule broken Typical message (Chrome in English)
required "Please fill out this field."
type="email" "Please include an '@' in the email address…"
minlength "Please lengthen this text to 2 characters or more…"
min / max "Value must be greater than or equal to 1."
step "Please enter a valid value. The two nearest valid values are…"
pattern "Please match the requested format." (+ the title, if there is one)

Characteristics:

  • They are in the browser's language, not your page's, and they vary from one browser to another.
  • Only one message at a time is displayed: the one for the first invalid field. Once that is corrected, the next one will appear when you submit again.
  • They cannot be changed with HTML or styled. Customising them requires JavaScript (for example, the setCustomValidity() method), which is outside the scope of this course.
  • Screen readers announce them.

For all these reasons, the most effective thing you can do in HTML is to prevent the error: clear labels, an asterisk on what is required and the format explained in visible text.

Styles based on validity (a brief mention)

CSS can style fields according to their state with pseudo-classes, like the ones for links mentioned in Module 3:

  • :required / :optional: required or optional fields.
  • :valid / :invalid: whether or not they meet their rules. Watch out: an empty required field is :invalid from the start, before the user has typed anything.
  • :user-invalid: invalid after the user has interacted with it; this is usually the best option for marking errors in red.

You will use them when you study CSS in Module 8 and when you integrate the form in Module 11.

Client-side validation is no substitute for server-side validation

This is the most important idea in the lesson. Everything you have learnt runs in the user's browser, and the user controls their browser. Anyone can bypass the validation:

  • With DevTools: by deleting required, pattern or max in the Elements tab before submitting. Try it in the project: it takes seconds.
  • With an old browser, or one that doesn't support a particular type or attribute.
  • Without a browser: a program (or a person with tools such as curl) can send data directly to the action URL, without going through your form.
graph LR
    A["User with a browser"] -->|"HTML validation: helps"| S["Server"]
    B["User who edits the HTML with DevTools"] -->|"no validation"| S
    C["Program or bot that sends data directly"] -->|"no validation"| S
    S --> V{"Does the server validate?"}
    V -->|"Yes"| OK["Data accepted, or rejected with a reason"]
    V -->|"No"| KO["Incorrect or malicious data stored"]

Therefore:

  • HTML validation is there for the convenience of honest users: it tells them straight away that they have made a mistake.
  • The server must check everything again: required fields, lengths, formats, ranges… and protect itself against malicious data.
  • Some rules can only be checked by the server: whether there are free tables that day, whether the workshop date really is the first Saturday of the month, whether today is a bank holiday, or whether the date is later than today (once the fixed min has gone out of date).

If you ever program the server, or hire someone to do it, make sure these checks exist.

Project: validating the booking form

Apply the rules to the form in bookings.html. These are The Blue Cup's decisions:

Field Rules Reason
Name Required, 2–60 characters, autocomplete="name" To know whose name the table is booked under
Email Required, max. 100, autocomplete="email" To send the confirmation
Phone Required, Spanish pattern, autocomplete="tel", example To warn of any problems on the day
Booking type Required A choice must always be made
Date Required, from 1 December 2026 to 31 March 2027 Bookings up to about three months in advance
Time Required, from 8:00 to 19:00, every 30 minutes The café closes at 20:00
Guests Required, from 1 to 12 Larger groups book by phone
Occasion Optional, max. 40 —
Comments Optional, max. 500 —
Privacy Required (checkbox ticked) Without acceptance the data cannot be processed

Replace the content of the form. Before the form, add the note about required fields:

    <p>Fields marked with * are required.</p>

    <!-- Booking form: method="get" is temporary so we can see the data in the URL; it will switch to post in lesson 05-06 -->
    <form action="https://forms.thebluecup.example/bookings" method="get">
      <input type="hidden" name="form" value="web-booking">

      <fieldset>
        <legend>Your details</legend>
        <p>
          <label for="name">Name *</label>
          <input type="text" id="name" name="name" required minlength="2" maxlength="60" autocomplete="name">
        </p>
        <p>
          <label for="email">Email *</label>
          <input type="email" id="email" name="email" required maxlength="100" autocomplete="email">
        </p>
        <p>
          <label for="phone">Phone *</label>
          <input type="tel" id="phone" name="phone" required
                 pattern="(\+34 ?)?[6-9]( ?[0-9]){8}"
                 title="9-digit Spanish phone number, with or without +34"
                 placeholder="600 000 000" autocomplete="tel">
          <br><small>9-digit Spanish phone number, with or without +34 and with or without spaces.</small>
        </p>
      </fieldset>

      <fieldset>
        <legend>Your booking</legend>
        <fieldset>
          <legend>What would you like to book? *</legend>
          <input type="radio" id="type-table" name="type" value="table" checked required>
          <label for="type-table">A table</label>
          <input type="radio" id="type-workshop" name="type" value="workshop" required>
          <label for="type-workshop">A place on the bread-making workshop (first Saturday of every month, 10:00–13:00)</label>
        </fieldset>
        <p>
          <!-- Update min and max periodically: HTML cannot work out "today" -->
          <label for="date">Date *</label>
          <input type="date" id="date" name="date" required min="2026-12-01" max="2027-03-31">
        </p>
        <p>
          <label for="time">Time *</label>
          <input type="time" id="time" name="time" required min="08:00" max="19:00" step="1800">
          <br><small>From 8:00 to 19:00, on the hour or half past.</small>
        </p>
        <p>
          <label for="guests">Number of guests *</label>
          <input type="number" id="guests" name="guests" required min="1" max="12" step="1" value="2">
          <br><small>Up to 12 people. For larger groups, call us on <a href="tel:+34900000000">+34&nbsp;900&nbsp;000&nbsp;000</a>.</small>
        </p>
        <p>
          <label for="occasion">Are you celebrating anything? (optional)</label>
          <input type="text" id="occasion" name="occasion" list="occasions" maxlength="40">
          <datalist id="occasions">
            <option value="Birthday">
            <option value="Anniversary">
            <option value="Farewell party">
            <option value="Work meeting">
            <option value="Christening or first communion">
          </datalist>
        </p>
      </fieldset>

      <fieldset>
        <legend>Preferences</legend>
        <fieldset>
          <legend>Area (table bookings only)</legend>
          <input type="radio" id="area-indoor" name="area" value="indoor" checked>
          <label for="area-indoor">Indoors</label>
          <input type="radio" id="area-terrace" name="area" value="terrace">
          <label for="area-terrace">Terrace</label>
        </fieldset>
        <p>
          <label for="comments">Comments (allergies, highchairs…)</label><br>
          <textarea id="comments" name="comments" rows="4" cols="40" maxlength="500"></textarea>
          <br><small>500 characters maximum.</small>
        </p>
      </fieldset>

      <p>
        <input type="checkbox" id="privacy" name="privacy" value="accept" required>
        <label for="privacy">I have read and accept the privacy policy *</label>
      </p>

      <p>
        <button type="submit">Send booking</button>
      </p>
    </form>

Some decisions worth explaining:

  • The help texts go in small after the field, as visible text. Later, in Using ARIA Roles and Attributes, you will learn to associate them with the field using aria-describedby so that the screen reader reads them along with the label.
  • The phone number for large groups is a tel: link, as on the rest of the site.
  • The "Area" radio buttons don't have required: one is already selected by default and, for the workshop, the area isn't used.
  • autofocus doesn't appear, on purpose.
  • The rule "the workshop is only on the first Saturday of the month, from 10:00 to 13:00" cannot be expressed with HTML attributes: the server will check it.

Tests

With Live Server, try submitting the form in these cases and observe the browser's message:

  1. Everything empty: the focus goes to "Name" with "Please fill out this field."
  2. Name "A": a minimum length warning.
  3. Phone "612-345-678": a format warning (perhaps with the title text).
  4. A date before 1 December 2026: a minimum value warning.
  5. Time 19:45 or 10:15: a maximum or step warning.
  6. 15 guests: a maximum value warning.
  7. Everything correct, without ticking the privacy checkbox: a warning on the checkbox.
  8. Everything correct: the form is submitted and you see the URL with the data.

Finally, carry out the test that proves the warning: in DevTools, in the Elements tab, delete the required attribute from the privacy checkbox and submit without ticking it. The form is submitted, and privacy doesn't appear in the URL. This is exactly what the server will have to detect and reject.

Common Mistakes and Tips

  • Believing that HTML validation is enough: it is a help for the user, not a protection. The server always validates again.
  • Using minlength or pattern without required: an empty field complies with them. If it is required, say so.
  • Writing min/max in a local format: min="01/12/2026" doesn't work; it is min="2026-12-01".
  • Forgetting that step on time is in seconds: step="30" is 30 seconds, not 30 minutes.
  • Overly strict patterns: rejecting spaces in a phone number, apostrophes in a surname (O'Connor) or short names forces users to fight with the form. Only be strict where necessary.
  • Patterns without a visible explanation: the generic pattern message doesn't say what format is expected.
  • Confusing readonly and disabled: the first is sent; the second isn't.
  • Putting autofocus on pages with content before the form: it harms screen reader users.
  • A maxlength that is too short: a real name that doesn't fit is a lost customer.
  • Tip: always test your forms by trying to break them: empty, with absurd data, using only the keyboard and on mobile. And also test submitting with novalidate to see what the server would receive in the worst case.

Exercises

Exercise 1. Write a required field for the membership number of The Blue Cup's customer club, which has the format BC- followed by exactly 4 digits (for example, BC-0427). Include a label, visible help and a suitable keyboard.

Exercise 2. State what is sent by this form if the user types "Lucy" in the name field and clicks the button, and explain why:

<form action="https://forms.thebluecup.example/test" method="get">
  <input type="text" name="name">
  <input type="text" name="premises" value="12 Example Street" readonly>
  <input type="text" name="coupon" value="AUTUMN26" disabled>
  <fieldset disabled>
    <input type="text" name="workshop" value="january">
  </fieldset>
  <button type="submit">Send</button>
</form>

Exercise 3. The Blue Cup takes cake orders for collection between 9:00 and 18:00, every 15 minutes, with a minimum of 8 portions and a maximum of 40, in multiples of 4. Write the collection time and number of portions fields, both required.

Solutions

Solution 1.

<p>
  <label for="member">Membership number *</label>
  <input type="text" id="member" name="member" required
         pattern="BC-[0-9]{4}" placeholder="BC-0000"
         title="BC- followed by 4 digits" maxlength="7">
  <br><small>Format: BC- followed by 4 digits, for example BC-0427.</small>
</p>
  • BC- are literal characters (outside square brackets, the hyphen has no special meaning); [0-9]{4} means four digits.
  • As the pattern is compared with the whole value, BC-04271 and bc-0427 are not valid (capitals count).
  • type="text" is used, not number, because it contains letters and a hyphen. inputmode="numeric" is not used, because the user needs to type BC-.
  • maxlength="7" prevents typing too much; required prevents leaving it empty.

Solution 2.

name=Lucy&premises=12+Example+Street
  • name: what was typed.
  • premises: readonly prevents it from being edited, but it is sent (with its spaces encoded as +).
  • coupon: disabled, so it is not sent.
  • workshop: it is inside a fieldset disabled, so it is also disabled and is not sent.

Solution 3.

<p>
  <label for="collection-time">Collection time *</label>
  <input type="time" id="collection-time" name="collection_time" required
         min="09:00" max="18:00" step="900">
  <br><small>From 9:00 to 18:00, every 15 minutes.</small>
</p>
<p>
  <label for="portions">Number of portions *</label>
  <input type="number" id="portions" name="portions" required
         min="8" max="40" step="4" value="8">
  <br><small>From 8 to 40 portions, in multiples of 4.</small>
</p>
  • 15 minutes is 900 seconds. From min="09:00": 9:00, 9:15, 9:30…
  • With min="8" and step="4", the valid values are 8, 12, 16… 40, which are exactly the multiples of 4 between 8 and 40. If min were 10, the valid values would be 10, 14, 18…: the step counts from min.

Conclusion

In this lesson you have learnt to set rules for data with HTML attributes: required for what is mandatory, minlength and maxlength for length, min, max and step for numbers, dates and times, and pattern with simple regular expressions for formats such as the phone number. You have also improved the experience of filling in the form with placeholder as an example, autocomplete with the standard names for data items and a cautious use of autofocus; you have distinguished readonly (sent) from disabled (not sent), seen how to turn validation off with novalidate and formnovalidate and how the native messages behave. And, above all, you have seen with your own eyes that browser validation can be bypassed in seconds, so the server must always validate again. The booking form now guides customers so that they send correct data. But it is still sending their name, email address and phone number in plain view in the URL, with the temporary get you set in the first lesson. In the next and final lesson of the module, Submitting Forms, you will study in depth how the data travels, switch the form to post, learn about the privacy obligations involved in collecting personal data and create the contact and newsletter forms.

HTML Course

Module 1: Introduction to HTML

Module 2: Text Formatting in HTML

Module 3: Links and Media in HTML

Module 4: Tables in HTML

Module 5: Forms in HTML

Module 6: HTML5 Semantic Elements

Module 7: Advanced HTML Techniques

Module 8: Integrating HTML and CSS

Module 9: Responsive Web Design

Module 10: Best Practices and Accessibility

Module 11: Project: Building a Complete Website

© Copyright 2026. All rights reserved