Free, independent guides since 2010

Code

HTML form validation without JavaScript

How to validate forms with built-in HTML attributes: required, type, pattern, min and max, length limits, autocomplete, styling valid and invalid fields, and when server-side checks are still needed.

<guide section="Code" type="guide" read="1 min"/>

Our classic tutorial making forms in HTML shows the building blocks. Modern HTML adds a lot of validation for free. Here is how to use it well.

Built-in validation attributes

HTML
<form action="/send" method="post">
  <label for="name">Name</label>
  <input id="name" name="name" required autocomplete="name">

  <label for="email">Email</label>
  <input id="email" name="email" type="email" required autocomplete="email">

  <label for="zip">Postcode</label>
  <input id="zip" name="zip" inputmode="numeric" pattern="[0-9]{4}"
         title="Four digits, for example 2000" autocomplete="postal-code">

  <label for="msg">Message</label>
  <textarea id="msg" name="message" required minlength="10" maxlength="2000"></textarea>

  <button>Send</button>
</form>

The attributes you need

AttributeEffect
requiredField must be filled
typeemail, url, tel, number, date… with matching keyboards on phones
patternRegular expression the value must match
min, max, stepLimits for numbers and dates
minlength, maxlengthLength limits for text
autocompleteLets browsers fill in known details
inputmodeChooses the on-screen keyboard

Styling valid and invalid fields

CSS
input:user-invalid { border-color: #a12a1d; }
input:user-valid { border-color: #2f6b4f; }

:user-invalid only applies after the user has interacted with the field, so the form does not shout errors before anyone has typed.

Accessible error messages

  • Every field needs a visible <label>.
  • Explain the expected format before the user makes a mistake.
  • Do not rely on colour alone to show errors.
  • Link error text to the field with aria-describedby.

Design tips for forms people actually complete: web forms UX.

Frequently asked questions

Is HTML validation enough for security?

No. Anyone can bypass browser validation. It improves user experience, but your server must check all input again.

Can I change the browser’s error messages?

Yes, with the Constraint Validation API in JavaScript, or by showing your own messages next to the fields. Keep them specific and polite.