Browser validation

Required values and length constraints

Declare required fields and sensible minimum or maximum lengths while keeping optional fields genuinely optional.

HTML can express the simple rules on its own. No JavaScript needed.

Here is a message field with three constraints:

<label for="message">Message</label>
<textarea
  id="message"
  name="message"
  required
  minlength="20"
  maxlength="1000"
></textarea>

required rejects an empty value. minlength and maxlength set the accepted length. Submit with 12 characters and the browser blocks the submission, focuses the textarea, and shows a message like “Please lengthen this text to 20 characters or more”.

The two length attributes behave a bit differently. maxlength stops you from typing past the limit, and trims pasted text. minlength only complains at submit time, and only if the person actually edited the field. A prefilled short value from the server doesn’t trigger it.

Choose limits from the real task

Pick numbers that come from what the field is for. A 20-character minimum makes sense for a support request. It makes no sense for a first name, where “Bo” is a real name.

Arbitrary limits reject real data and annoy real people. When you can’t explain why a limit exists, drop it.

Don’t require everything

Ask only for what the current task needs. If the phone number is optional, leave required off. A shorter form gets completed more often, is easier to validate, and stores less data you’re responsible for.

Whitespace

Spaces need a decision. A message made of 25 spaces passes a minlength="20" check, and it’s still empty.

On the server, trim where it makes sense, then check whether anything meaningful is left. But be careful. Don’t trim passwords. A space at the end of a password may be intentional, and trimming it locks the person out.

Characters are not bytes

maxlength counts characters the way JavaScript’s .length does, in UTF-16 code units. An emoji counts as two. Your database column may count bytes, where the same emoji takes four.

Give the database a little headroom, or check the byte length on the server as well. A message that passes in the browser and fails with a database error is a confusing experience.

The browser is not the authority

Everything above is user feedback. Someone can send a request straight to your endpoint with an empty message or a 50,000-character one. The server must check presence and length again before saving anything.

Try this: submit the textarea with nothing, with 19 characters, with 20, and with 1001. The browser should block three of the four. Then send the same four bodies with curl and confirm the server draws the lines in exactly the same places.

Lesson completed