Menu
Forms & Inputs

HTML Form Validation

required, pattern, min/max, minlength/maxlength.

1Validation Without JS

Browsers can validate inputs before submission using attributes. Add required, pattern, min, max, minlength, maxlength, and the browser shows a built-in error.

Example Code
css
<form>
  <input
    name="username"
    required
    minlength="3"
    maxlength="20"
    pattern="[A-Za-z0-9_]+"
    title="Letters, numbers, underscore"
  />
  <input type="email" required />
  <input type="number" min="18" max="120" required />
  <button>Submit</button>
</form>

2Put the element in context

Browser validation can guide users, but it is not a security boundary. Validate again where submissions are received. Errors should explain the issue in words, remain associated with the relevant field, and preserve information the visitor has already entered.

3Practice with a small page

Test an empty required field and a malformed email address. Add a useful error message and check that it is discoverable with keyboard navigation. Simulate a failed submission and ensure the message content is not erased when the visitor tries again.

Finished reading?

Mark this topic as complete to track progress.