Lesson 5 of 12 · 11 min · HTML and CSS

HTML forms: inputs, labels and validation

Covers: Current HTML Living Standard. Updated 13 Nov 2026. Part of the Frontend Developer roadmap.

What you will learn

  • Build a form with <form>, <label>, <input>, <select>, <textarea> and <button>
  • Pick the right input type, autocomplete and inputmode
  • Use built-in validation attributes and style the result
  • Understand how a form is submitted (GET, POST, enctype)
  • Why the server must always validate again

In simple words

A form is how a web page asks a person for information: a login box, a sign-up page, a search bar, an application. Good forms are easy to fill in on a phone, tell you clearly what went wrong, and never lose what you typed. The browser already does a lot of the work, such as showing the right keyboard and checking an email address, if you use the right HTML.

Words to know

  • Form control: an input, drop-down, text area or button inside a form.
  • Label: the text that names a form control and is connected to it.
  • Validation: checking that the data entered meets the rules.
  • Submit: sending the form's data to the server.

A first form

<form action="/signup" method="post">
  <p>
    <label for="name">Full name</label>
    <input id="name" name="name" type="text" autocomplete="name" required>
  </p>
  <p>
    <label for="email">Email address</label>
    <input id="email" name="email" type="email" autocomplete="email" required>
  </p>
  <p>
    <label for="phone">Mobile number</label>
    <input id="phone" name="phone" type="tel" autocomplete="tel" inputmode="numeric"
           pattern="[6-9][0-9]{9}" title="10 digits starting with 6, 7, 8 or 9">
  </p>
  <p>
    <label for="role">Target job</label>
    <select id="role" name="role" required>
      <option value="">Choose one</option>
      <option value="data-analyst">Data Analyst</option>
      <option value="java-developer">Java Developer</option>
    </select>
  </p>
  <button type="submit">Create account</button>
</form>

Key points:

  • Every control needs a label connected with for and id (or by wrapping the input inside the <label>). A placeholder is not a label: it disappears when you type and has poor contrast.
  • The name attribute is the key sent to the server; a control without name is not submitted.
  • <button type="submit"> submits; type="button" does nothing by itself (use it for buttons that run JavaScript); type="reset" clears the form (rarely a good idea).
  • Pressing Enter in a text field submits the form, so use a real <form> and a submit button instead of a click handler on a <div>.

Input types

The type attribute chooses the control, the keyboard on phones, and built-in checks:

Type For Notes
text, search free text
email email address checks the format; mobile keyboard shows @
tel phone number numeric keypad; no format check (use pattern)
url web address
number numbers min, max, step; poor for phone numbers, PIN codes and IDs (use text with inputmode="numeric")
password secret text hides characters
date, time, datetime-local, month dates and times native pickers
checkbox yes or no, or several choices
radio one choice from a group same name for the group
file upload accept="image/*", multiple
range, color sliders, colours
hidden data the user does not see never trust it: users can change it

Other controls: <textarea rows="4"> for long text, <select> with <option> (and <optgroup>), <datalist> for suggestions, <output>, <progress>, <meter>.

Group related controls (radio buttons, an address) with a <fieldset> and a <legend>, which screen readers announce as the question:

<fieldset>
  <legend>How do you prefer to practise?</legend>
  <label><input type="radio" name="mode" value="written" checked> Written answers</label>
  <label><input type="radio" name="mode" value="voice"> Voice answers</label>
</fieldset>

Help the browser help the user

  • autocomplete with standard tokens (name, email, tel, username, current-password, new-password, one-time-code, postal-code, street-address) lets browsers and password managers fill the form (it is also a WCAG requirement for personal data).
  • inputmode picks the mobile keyboard (numeric, decimal, email, tel, search); enterkeyhint labels the Enter key.
  • autofocus sparingly; spellcheck, autocapitalize where useful (turn off for emails and usernames).
  • For one-time passwords: autocomplete="one-time-code" inputmode="numeric" lets phones suggest the SMS code.
  • Do not block paste in password fields.

Built-in validation

HTML checks input before submitting, with no JavaScript:

Attribute Rule
required must not be empty
minlength, maxlength text length
min, max, step numbers and dates
pattern regular expression the whole value must match
type="email", type="url" format checks

When a rule fails, the browser blocks the submit and shows a message next to the first invalid field. Style states with CSS, but be careful to show errors only after the user has interacted:

input:user-invalid { border-color: #b3261e; }       /* only after the user touched it */
input:user-valid   { border-color: #2e7d32; }

(:invalid alone would show red on an empty form before anyone types; :user-invalid waits.) For custom messages and live feedback use the Constraint Validation API in JavaScript: input.setCustomValidity("Message"), form.checkValidity(), input.validity.valueMissing, form.reportValidity(), and add novalidate on the form if you take over completely.

Write helpful errors: say what is wrong and how to fix it ("Enter a 10-digit mobile number starting with 6 to 9"), put the message next to the field, link it with aria-describedby, mark the field aria-invalid="true", and move focus to the first error or a summary at the top. Do not rely on red colour alone. Do not clear the fields when there is an error.

Server-side validation is mandatory

Client-side validation is for convenience: quick feedback. It is not security. Anyone can bypass the browser with curl, edit the HTML in DevTools, or send forged requests. The server must validate everything again: types, ranges, lengths, allowed values, required fields (the Spring Boot course shows Bean Validation). Also protect against CSRF (anti-forgery tokens or SameSite cookies), escape output to prevent XSS, use parameterised queries against SQL injection, limit upload types and sizes, and rate-limit login and sign-up. Never put prices, roles or user ids in hidden fields and trust them.

Designing forms people finish

  • Ask only for what you need; every extra field loses people.
  • One column, labels above fields, fields as wide as the expected input.
  • Mark required fields (or mark the optional ones) clearly, and explain formats before the field, not only in an error.
  • Use the right input types and autocomplete, so phones do the typing.
  • Keep the submit button's label specific ("Create account", not "Submit"), make it large enough to tap and disable it only with care (a disabled button gives no explanation).
  • Show progress in long forms and allow going back without losing data.
  • Show a clear confirmation after success.
  • Respect Indian context: names do not have a first and last name pattern (use one "Full name" field), mobile numbers are the main identifier, PIN codes are 6 digits, many users type in more than one script, and OTP by SMS is common.

Common mistakes

  • Placeholders instead of labels.
  • Missing name, for/id or type.
  • Using type="number" for phone numbers, PIN codes or card numbers.
  • Relying only on client-side validation.
  • Red borders on an untouched form (use :user-invalid).
  • Clearing the form on error.
  • Using GET for sensitive data.
  • Click handlers on divs instead of submit buttons.

Try it yourself

  1. Build the sign-up form above with labels, required, type="email" and a pattern for an Indian mobile number.
  2. Add autocomplete and inputmode, and open it on a phone to see the keyboards.
  3. Style invalid fields with :user-invalid and write one helpful error message with aria-describedby.
  4. Submit with curl a value the browser would have rejected, and note that your server must reject it.
  5. Convert the form to submit with fetch and FormData, keeping a working non-JavaScript version.

Check yourself

Why should every input have a <label>?

Labels name the control for screen reader users and enlarge the click and tap target, and unlike placeholders they stay visible while typing.

When do you use GET and when POST for a form?

GET for safe, repeatable actions like searches and filters, since the data appears in the URL; POST for creating or changing data and for anything sensitive.

Is HTML validation enough to protect your application?

No. It is a convenience; anyone can bypass the browser, so the server must validate all input again.

What does :user-invalid do compared to :invalid?

It matches an invalid field only after the user has interacted with it, avoiding red errors on an untouched form.

Interview questions

How do you validate a form in HTML and why also on the server?

Use attributes such as required, type, pattern, min and max for immediate feedback; the server must repeat the checks because client-side checks can be bypassed.

What is the difference between name and id on an input?

name is the key submitted to the server; id uniquely identifies the element in the page, for labels, CSS and scripts.

How would you make a form accessible?

Connect labels to every control, group related controls with fieldset and legend, use correct types and autocomplete, give clear error messages linked with aria-describedby, ensure keyboard operation and visible focus, and do not rely on colour alone.

Summary

  • Use a real <form> with labels connected to inputs, the right type, name, autocomplete and inputmode.
  • Built-in attributes validate on the client; style with :user-invalid; write helpful, accessible errors.
  • GET for searches, POST for changes; use FormData and fetch as progressive enhancement.
  • Server-side validation and security are mandatory.

Going deeper

See how much of this you can explain

A free mock interview asks you new questions on HTML, CSS and how the web works for Frontend Developer and scores every answer, with what to fix.