Input types and built-in validation

HTML · Practical · 12 min

The right input type gives mobile users the right keyboard and gets you free validation and pickers.

<input> has over twenty type values, and choosing well improves forms immediately.

  • email, url, tel: on phones these bring up keyboards with @, / or digits. email and url are also validated.
  • number (with min, max, step), range for a slider, date, time, datetime-local, month: native pickers.
  • checkbox, radio, color, file (with accept="image/*" and multiple), search, password, hidden.

Constraint attributes let the browser validate before submitting: required, minlength/maxlength, min/max, step, and pattern (a regular expression that must match the whole value). On submit, the first invalid field gets focus and a native message. The CSS pseudo-classes :invalid and :user-invalid style fields; :user-invalid only applies after the user has interacted, so empty required fields aren't red on page load.

autocomplete tokens such as email, name, street-address, new-password, current-password and one-time-code let browsers and password managers fill fields correctly. inputmode="numeric" asks for a digit keyboard without number semantics, which is better than type="number" for things like card numbers and postcodes, where arrows and scroll-wheel changes make no sense.

Client-side validation is a convenience for users, not security. Anyone can bypass it, so the server must validate everything again.

Example

<form>
  <label>Email <input type="email" name="email" autocomplete="email" required></label>

  <label>Age <input type="number" name="age" min="13" max="120" step="1"></label>

  <label>Postcode
    <input name="zip" inputmode="numeric" pattern="[0-9]{5}" autocomplete="postal-code"
           title="Five digits">
  </label>

  <label>Start date <input type="date" name="start" min="2026-01-01"></label>

  <label>Avatar <input type="file" name="avatar" accept="image/*"></label>

  <label>New password
    <input type="password" name="pw" minlength="12" autocomplete="new-password" required>
  </label>
  <button>Save</button>
</form>

Remember

  • Specific input types give the right mobile keyboard and native pickers
  • required, pattern, min/max and minlength validate before submit
  • autocomplete tokens help browsers fill forms
  • Always validate again on the server

Watch out for

  • Using type="number" for card numbers or postcodes; use inputmode="numeric" with pattern.

Check yourself

  1. An input has pattern="[0-9]{3}". Which value passes validation?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/input