Only accept a valid code

Accept a four-digit postal code, and nothing else.

What to build

One text input with a rule.

Requirements

  • An input named code, labelled Postal code.
  • required.
  • A pattern that accepts exactly four digits.
  • A title containing the word digits.

Constraints

Use a text input, since a postal code is not a quantity.

Example

1207 is valid. 12a7 and 12070 are not.

Why it works

pattern must match the entire value, so one short pattern rules out everything except four digits.

Hints

Hint 1

Square brackets list allowed characters. Curly brackets say how many.

Hint 2

Remember required, because an empty value passes a pattern.

Hint 3

A title tells people the format.

Solution

Show one correct solution (try it yourself first)
<form>
  <label for="c">Postal code</label>
  <input id="c" name="code" required pattern="[0-9]{4}" title="Exactly 4 digits, like 1207">
  <button>Save</button>
</form>

Lesson: Checking answers before they are sent →