🌱BeginnerForms

Form Validation

Add built-in browser validation with required, minlength, maxlength, min, max, and pattern.

Overview

HTML5 provides built-in form validation that runs before the form is submitted, without needing JavaScript. This "constraint validation" checks that values meet specified rules and shows native browser error messages. Key validation attributes: - required: field must have a value - minlength / maxlength: character count constraints (text inputs) - min / max: value constraints (number, date, range inputs) - pattern: a regex the value must match - type: email, url, number types automatically validate format While HTML validation is a good first line of defense, always validate on the server too HTML validation can be bypassed.

Key Points

  • •required prevents submission of empty mandatory fields
  • •minlength/maxlength limit character count in text, search, url, tel, password inputs
  • •min/max constrain numeric, date, and range values
  • •pattern accepts a regex (no surrounding //) e.g. pattern="[A-Za-z]+"
  • •title on a field with pattern provides a custom validation hint
  • •CSS :valid and :invalid pseudo-classes let you style fields based on validation state

Examples

Required and length constraints

<form>
  <label for="username">Username (3-16 characters)</label>
  <input
    type="text"
    id="username"
    name="username"
    required
    minlength="3"
    maxlength="16"
  >

  <label for="password">Password (min 8 characters)</label>
  <input
    type="password"
    id="password"
    name="password"
    required
    minlength="8"
  >

  <button type="submit">Sign Up</button>
</form>

Number constraints and pattern matching

<!-- Age: 18 to 120 -->
<input type="number" name="age" min="18" max="120" required>

<!-- UK postcode pattern -->
<input
  type="text"
  name="postcode"
  pattern="[A-Z]{1,2}[0-9][0-9A-Z]? [0-9][A-Z]{2}"
  title="Enter a valid UK postcode (e.g. SW1A 1AA)"
  required
>

CSS for validation feedback

<style>
  input:valid   { border: 2px solid green; }
  input:invalid { border: 2px solid red; }
  /* Only show invalid styles after user interaction */
  input:not(:focus):not(:placeholder-shown):invalid {
    border-color: red;
  }
</style>

Common Mistakes

  • Relying on HTML validation alone always validate on the server; client-side can be bypassed
  • Pattern regex that is too strict frustrating users who enter valid formats you didn't anticipate
  • Using required on every field only truly required fields should block submission

Note

HTML validation is UX improvement, not security. A determined user can remove the required attribute in DevTools. Always validate and sanitize on the server side.

Exercises

Write HTML to solve each exercise. Use Preview to see it render in a live iframe, then mark as done.

Loading editor…

Completed: 0 / 5 exercises

Knowledge Check

Question 1 of 4

What does the required attribute do on an <input>?