CHAPTER 35 · HTML

Form validation: help people correct missing or unsuitable answers

A clear form explains what it needs and helps readers fix mistakes. Use native HTML constraints for common checks, test valid and invalid cases, and understand why a real receiving application must check the data again.

Download example files (ZIP)

Validation means checking a rule

A library desk may ask for a student code before accepting a request. An empty space is not enough; a code in the wrong format may also need correction. Validation is checking whether an answer follows a stated rule.

HTML can describe several rules without JavaScript: a required answer, an email-shaped value, a text-length range or a number between limits. The browser normally checks eligible controls during ordinary validated submission and can show a message. Message wording and presentation vary by browser and language.

Good instructions come before the mistake. Do not hide an important rule only inside an error message or a hover title.

Required and optional are different

Required is boolean: its presence asks for a value on a supported control. Required="false" still includes it. Remove the attribute to make the control optional.

An optional email field can be empty and valid; a non-empty value must still satisfy the email type check. Required on an ordinary text field checks for emptiness, not whether a person typed a meaningful answer. Spaces are not automatically trimmed into a useful name. Real services need appropriate checks for their actual requirements.

Text length and a simple format rule

Minlength and maxlength describe text-length limits for supported text-entry controls. They do not set the visible field width; size has that different job. For these exercises, use ordinary English letters and digits. Some symbols and emojis can count differently from the number of visible shapes you see.

Pattern describes an allowed format using a regular expression, a compact pattern notation. Our small example is [A-Z]{2}[0-9]{3}: two uppercase English letters followed by three digits. The browser tests the whole non-empty value, not just whether part of it matches. Do not surround the attribute value with slash characters as if it were a JavaScript expression.

HTML fragment — part of a document
<label for="student-code">Practice student code</label>
<p id="code-help">Use two uppercase letters and three digits, for example AB123.</p>
<input type="text" id="student-code" name="student_code" pattern="[A-Z]{2}[0-9]{3}" required aria-describedby="code-help">

Aria-describedby connects the field to its persistent instruction paragraph. Pattern alone does not make an optional empty field invalid. Required handles the missing answer separately. This is a made-up code rule, not a rule for every college or every person's name.

Teach the rule before checking it
  1. 1Explain the required answer
  2. 2Choose a suitable input type
  3. 3Add specific native constraints
  4. 4Test valid and invalid cases

A real receiving service must enforce appropriate rules again. Browser checks can be bypassed.

Complete program: code-validation.html

Save form-result.html from Chapter 31 beside this program. Test submission in your own browser; the embedded preview does not submit forms.

code-validation.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Check a Fictional Practice Code</title>
</head>
<body>
  <h1>Check the practice code format</h1>
  <p>These are invented practice values, not real student records.</p>
  <form action="form-result.html" method="get">
    <p><label for="alias">Practice alias (required, 2 to 20 characters)</label></p>
    <p><input type="text" id="alias" name="alias" minlength="2" maxlength="20" required></p>
    <p><label for="student-code">Practice student code (required)</label></p>
    <p id="code-help">Use two uppercase letters and three digits, for example AB123.</p>
    <p><input type="text" id="student-code" name="student_code" pattern="[A-Z]{2}[0-9]{3}" required aria-describedby="code-help"></p>
    <button type="submit">Check and inspect the values</button>
  </form>
</body>
</html>
Browser previewDocument title: Check a Fictional Practice Code

This preview shows the example in a browser. Save the complete code in local files to test links between pages and downloads. Same-page section links work here. Form submission is disabled in this preview. Save the example and its result page locally to test submission. Use fictional practice values.

Expected result: empty required fields cannot complete an ordinary validated submission. Try alias Learner with code AB123, then try ab123, AB12 and XAB123. Only AB123 matches the demonstrated code pattern. The pattern does not check that a real student code was issued.

Minlength checks are associated with user-edited values; do not assume that setting a short value through a script exercises every native validation path identically. Test the actual typing and submission interaction as well as any automated checks.

Numeric values: min, max and step

Type="number" describes a numeric quantity. Min and max set inclusive bounds. Step sets allowed increments, using the type's step-base rules. With min="1" and step="1", whole-number values from that base are valid; a value such as 2.5 has a step mismatch.

HTML fragment — part of a document
<input type="number" id="sessions" name="sessions" min="1" max="6" step="1" required>

Step="any" removes the step-increment restriction, but does not remove min, max or the requirement for a valid number. For decimal quantities, choose an appropriate step and explain the expected precision. Do not use a number control for a code whose leading zeroes must be preserved.

Range also represents a numeric value, usually through a slider. Its current numeric value is not automatically printed in an output element just because that output is nearby; live custom displays need additional behaviour. A slider can suit approximate preferences better than precise numeric entry.

Dates and clear boundaries

Type="date" supplies a date control where supported. Its submitted value uses year-month-day form, such as 2027-01-09, even if the displayed picker uses a local date format. Min and max can bound the permitted dates using that same form.

Date has no time zone or time-of-day component. Datetime-local likewise does not include a time-zone offset. A real event booking needs clear time-zone rules where time matters; a picker does not invent those rules.

Complete program: quantity-date.html

quantity-date.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Check a Practice Quantity and Date</title>
</head>
<body>
  <h1>Set a fictional practice plan</h1>
  <form action="form-result.html" method="get">
    <p><label for="sessions">Number of sessions (1 to 6 whole sessions)</label></p>
    <p><input type="number" id="sessions" name="sessions" min="1" max="6" step="1" value="2" required></p>
    <p><label for="practice-date">Practice date during 2027</label></p>
    <p><input type="date" id="practice-date" name="date" min="2027-01-01" max="2027-12-31" value="2027-01-09" required></p>
    <p><label for="plan-code">Practice plan code</label></p>
    <p><input type="text" id="plan-code" name="plan_code" value="RD-01" readonly></p>
    <p><label for="unavailable-room">Unavailable room choice</label></p>
    <p><input type="text" id="unavailable-room" name="unavailable_room" value="Room 9" disabled></p>
    <button type="submit">Check the practice plan</button>
  </form>
</body>
</html>
Browser previewDocument title: Check a Practice Quantity and Date

This preview shows the example in a browser. Save the complete code in local files to test links between pages and downloads. Same-page section links work here. Form submission is disabled in this preview. Save the example and its result page locally to test submission. Use fictional practice values.

Expected result: the initial values satisfy the numeric and date rules. Try sessions 0, 7 and 2.5, then restore 2. Try a date outside 2027. In a valid local submission, plan_code is included while unavailable_room is absent.

Readonly is different from disabled

A supported readonly field cannot be edited normally, but its named value can still be submitted and it can usually receive focus. A disabled control is excluded from submission and normally from sequential keyboard focus.

Neither state makes client data trustworthy. A visitor can alter the document or send a different request. Some constraints, including required, do not apply in the same way to readonly or disabled fields. Do not add readonly to hide an invalid value and call that a validation solution.

Required choices and deliberate bypasses

A normal required single dropdown can begin with a direct empty-value option such as Choose a room. The reader must choose a real value. A required radio group needs one selected answer, whereas required on a checkbox applies to that checkbox individually.

Novalidate on form suppresses interactive constraint validation for that form's submissions. Formnovalidate on a submit button can bypass it for that button. They do not fix invalid data. Use such behaviour only when the flow calls for it, for example a separately designed Save draft action whose receiving service handles incomplete data appropriately.

Browser checks do not protect a server

People can bypass the page, edit attributes or send requests directly. Therefore the receiving application must repeat appropriate checks before trusting or storing data. Native browser checks improve the entry experience; they are not an access-control boundary.

HTML also does not automatically check that two password fields match, that one date follows another, that a username is free or that a file is safe. Those rules need additional logic and suitable receiving-side checks.

Problem and solution: an optional pattern field accepts an empty answer

Problem: a student adds pattern and expects it to require an answer too.

Solution: decide whether an answer is mandatory. If so, add required and explain the rule visibly. Keep the two ideas separate: required checks for a missing value, while pattern constrains a non-empty value on supported types.

Common mistakes and useful tips

  • Using required="false" to mean optional.
  • Treating placeholder or title as the only format instruction.
  • Expecting minlength to make an otherwise optional field mandatory.
  • Using pattern on number as though it were a text format rule.
  • Forgetting step when accepting decimal quantities.
  • Assuming picker appearance equals a specific submitted date format.
  • Treating native validation as a replacement for receiving-side checks.

Practice questions

  1. What is validation?
  2. Why can an optional empty pattern field still be valid?
  3. Which of AB123, ab123 and XAB123 matches the demonstrated pattern?
  4. Why is 2.5 unsuitable for min="1" step="1" in the session-count example?
  5. Which named field is excluded from the second program's data: readonly plan_code or disabled unavailable_room?
  6. Save both examples and their result page. Test missing answers, the demonstrated invalid codes, numeric bounds and a date outside 2027. Then restore valid fictional values and inspect the submitted entries.
Check your practice answers
  1. Checking an answer against a stated rule.
  2. Pattern checks a non-empty value. Required is the separate missing-value constraint.
  3. AB123 only: the rule is exactly two uppercase English letters followed by three digits.
  4. It is not a whole step from the specified base of 1. A fractional session does not fit this task.
  5. Disabled unavailable_room is excluded. Named readonly plan_code is included under ordinary submission rules.
  6. Empty required fields and unsuitable constrained values should prevent ordinary validated submission in the saved examples. Valid values reach the local destination, but no server storage or real student verification occurs.

Interview questions

What is the benefit of native validation?

It can identify common entry mistakes before submission using standard control types and constraints. It reduces avoidable errors while still needing clear instructions and receiving-side checks.

How do min, max and maxlength differ?

Min and max bound supported numeric or date-like values. Maxlength limits user-entered text length on supported text controls. They are not interchangeable properties.

Does an accepted email or code prove that it exists?

No. A format check proves only that the value satisfies that format rule. Existence, ownership and permissions require additional appropriate checks.

Why validate again on the receiving side?

The receiving service can receive data that never passed through the intended browser form. It must enforce its own rules before trusting, storing or acting on the values.

Quick revision

  • State the rule visibly, then add the matching native constraint.
  • Required, pattern, length limits and numeric/date bounds have different jobs.
  • Readonly and disabled have different submission behaviour.
  • Test both valid and invalid cases and recheck all trusted rules on the receiving side.