Browser validation

Patterns and formats

Use native type validation and regular-expression patterns only when the accepted format is narrow, stable, and clearly explained.

8 minute lesson

~~~

Start with a native type. Email and URL inputs already provide basic format validation and suitable input behavior.

Use pattern only when the accepted format is narrow and stable. For example, a project code might be exactly three uppercase letters followed by four digits:

<label for="project">Project code</label>
<p id="project-help">Use the format ABC-1234.</p>
<input
  id="project"
  name="project"
  pattern="[A-Z]{3}-[0-9]{4}"
  aria-describedby="project-help"
  required
>

The pattern should describe the whole accepted value. Explain it in normal language before the person submits.

Avoid complicated regular expressions for names, postal addresses, telephone numbers, and email addresses. Real-world values are more varied than they first appear. A narrow rule often blocks legitimate people while doing little for security.

Format is only one kind of validation. ABC-1234 may match the pattern but refer to no existing project. The server must perform that semantic check.

The server must also enforce the same syntax. Browser validation can be skipped, and clients can submit values that never appeared in the form.

Write down five valid values and five invalid values before adding a pattern. If the rule is hard to explain or rejects plausible input, use a simpler constraint and validate the business meaning on the server.

Lesson completed