HTML Forms and Validation

  • Admin
  • 2 min read

Building a Basic Form

<form action="/submit" method="POST"> <label for="email">Email</label> <input type="email" id="email" name="email" required> <label for="password">Password</label> <input type="password" id="password" name="password" minlength="8" required> <button type="submit">Sign Up</button> </form>

Built-In Validation Attributes

Modern browsers validate forms for you — no JavaScript required for the basics:

  • required — field can’t be empty
  • type="email" / type="url" — format checking
  • minlength / maxlength — text length limits
  • pattern — custom regex validation
  • min / max — for number and date inputs

Styling Valid/Invalid States

input:invalid { border-color: #dc2626; } input:valid { border-color: #16a34a; } /* Avoid showing red before the user has typed anything: */ input:placeholder-shown:invalid { border-color: #e5e7eb; }

Custom Validation with JavaScript

For rules HTML can’t express — like “password must match confirm password” — use the Constraint Validation API:

const confirmField = document.querySelector("#confirm"); confirmField.addEventListener("input", () => { const match = confirmField.value === passwordField.value; confirmField.setCustomValidity(match ? "" : "Passwords don't match"); });

Accessibility Basics

Always pair a visible <label> with its input using matching for/id attributes — this helps screen readers and lets users click the label to focus the field.

Practice Exercise

Build a signup form with name, email, password, and confirm-password fields, using only HTML validation attributes plus one JavaScript check for matching passwords.

Admin

About the author

Admin

Instructor and technical writer at tutorials.in

Writes beginner lessons for tutorials.in. Each lesson is checked against the language or tool documentation, and examples are run before publishing.

Reviewed by the editorial team before publishing. Last updated August 9, 2026.

Ask a question

Be specific about what you tried. Questions with a code sample and the exact error message are answered fastest.