CSS

HTML Forms and Validation

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.

Leave a Reply

Your email address will not be published. Required fields are marked *