# Built-in Form Validation

> HTML validation attributes describe constraints directly in the markup. The browser enforces them on submit and exposes them through CSS pseudo-classes and the Constraint Validation API, so you can style invalid fields and read error reasons in JavaScript without reinventing the logic.

Subject: HTML | Lesson 30 of 42 | 6 min read
Interactive lesson: https://codewithanimation.in/html/form-validation
Previous: [Grouping & Gauges](https://codewithanimation.in/html/fieldset-and-gauges.md) | Next: [Semantic Markup vs Div Soup](https://codewithanimation.in/html/semantic-vs-div-soup.md)

## What it is

HTML provides a set of attributes that declare constraints on form field values. `required` means the field must not be empty. `minlength` and `maxlength` bound the length of text. `min` and `max` bound numeric values. `pattern` takes a regular expression the value must match (the pattern is implicitly anchored to the full value, so `[0-9]{5}` matches exactly five digits with no extra characters). `type="email"` and `type="url"` validate format as well as collecting input. These attributes are checked by the browser automatically when the user submits the form.

The Constraint Validation API exposes the validation state of any input through its `validity` property, a `ValidityState` object with boolean flags: `valueMissing` (required field is empty), `typeMismatch` (value does not match the type's format), `patternMismatch` (value does not match `pattern`), `tooShort`/`tooLong`, `rangeUnderflow`/`rangeOverflow`, and `valid` (all constraints pass). `input.checkValidity()` returns a boolean and fires the `invalid` event on failure. `input.reportValidity()` does the same and also shows the browser's built-in tooltip. `input.setCustomValidity(message)` marks the field invalid with a custom message; call it with an empty string to clear the custom error.

## Why it matters

Built-in validation runs before any JavaScript, including your own. A form with `required` on every field prevents submission with empty values even if JavaScript is blocked or has not loaded yet. This is not a replacement for server-side validation (never trust the client), but it is a useful first line of feedback that costs no code to implement.

The CSS pseudo-classes `:valid` and `:invalid` let you style fields based on their constraint state. A green border on a valid email field and a red border on an invalid one are achievable with two CSS rules and zero JavaScript. The `pattern` attribute used with `:invalid` can show error styling as the user types, giving immediate feedback without a submit attempt.

## How it works

Add validation attributes to the relevant inputs. The browser checks them on submit and, if any field is invalid, prevents submission, focuses the first invalid field, and shows a localised tooltip with the reason. You can customise which message appears by calling `setCustomValidity()` in an `input` event handler before the browser validation runs.

To style fields based on validity, use `:valid` and `:invalid` in CSS. For a better user experience, use `:user-invalid` and `:user-valid` (supported in all modern browsers), which only apply after the user has interacted with the field. The problem with plain `:invalid` is that it fires on page load: an empty `required` field is technically invalid from the moment the page renders, so it turns red before the user has had a chance to type anything.

Add `novalidate` to the `<form>` element to opt out of browser built-in validation entirely. You might do this when you are implementing custom validation UI with JavaScript, or when using a form library that handles its own error messages. The Constraint Validation API still works on the individual inputs; `novalidate` only suppresses the automatic check on submit and the browser tooltip.

## Common mistake: Using :invalid instead of :user-invalid and seeing all fields go red on load

When you write `input:invalid { border-color: red }`, every empty `required` field on the page turns red the moment it renders. A sign-up form with five required fields greets the user with five red borders before they have touched anything. The fix is to use `input:user-invalid { border-color: red }` instead. This pseudo-class only activates after the field has been interacted with, matching the user's expectation that feedback appears in response to what they did, not before they started.

## Tip: Read input.validity to build precise error messages without duplicating the logic

When you need to show your own error message instead of the browser's tooltip, read the specific flag on `validity` that is true: `if (input.validity.valueMissing)` shows "This field is required"; `if (input.validity.typeMismatch)` shows "Please enter a valid email"; `if (input.validity.patternMismatch)` shows a pattern-specific hint. This lets you keep the browser's constraint logic (which handles edge cases you would forget) while controlling the copy shown to the user.

## Try it: Try it

Type into each field and watch the border flip as constraints are met or broken. Hit the submit button to trigger the browser's built-in validation UI.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/html/form-validation

## Check yourself

### Question 1

A sign-up form uses input:invalid { border-color: red }. Users see red borders before typing anything. What is the fix?

- A. Replace :invalid with :user-invalid, which only fires after user interaction
- B. Add novalidate to the form to prevent the red borders
- C. Remove the required attribute so fields are not invalid on load

Correct answer: A

`:invalid` fires immediately for empty `required` fields. `:user-invalid` is the same constraint check but waits until the user has interacted with the field, giving feedback only after they have had a chance to type.

- Why not B: novalidate disables built-in submit validation entirely. The :invalid pseudo-class is independent of novalidate and would still apply. :user-invalid is the correct selector.
- Why not C: Removing required defeats the purpose of validation. The issue is which CSS pseudo-class is used, not whether the field is required.

### Question 2

An input has pattern="[0-9]{5}". Does the value "12345abc" pass validation?

- A. No. The pattern is implicitly anchored, so the entire value must match
- B. Yes. The pattern finds the five-digit sequence within the string
- C. Yes, because the string contains exactly five digits somewhere

Correct answer: A

The `pattern` attribute is implicitly anchored: the browser checks whether the entire value matches the pattern, not whether the pattern can be found somewhere inside it.

- Why not B: Unlike a regex search, the pattern attribute is implicitly anchored. It must match the complete value, not just a substring. "12345abc" fails because the full string does not match [0-9]{5}.
- Why not C: Pattern matching is not a search. The browser tests whether the entire value matches the pattern. The trailing "abc" makes the whole value fail [0-9]{5}.

### Question 3

You called input.setCustomValidity("Username taken"). How do you clear the custom error later?

- A. Call input.setCustomValidity("") with an empty string
- B. Call input.setCustomValidity() with no argument
- C. Remove the custom message by calling input.clearValidity()

Correct answer: A

`setCustomValidity("")` marks the field valid again by clearing the custom message. Any non-empty string passed to the method marks the field invalid with that message as the browser tooltip.

- Why not B: Calling setCustomValidity with no argument passes undefined, which is coerced to the string "undefined", marking the field invalid with that message. An empty string is required to clear the custom error.
- Why not C: There is no clearValidity method. The only way to clear a custom validity message is to call setCustomValidity with an empty string.

## Remember this

- `pattern` is implicitly anchored: the entire value must match, not just a substring.
- `:invalid` fires on page load for empty required fields; use `:user-invalid` to show errors only after the user has interacted.
- `setCustomValidity(message)` marks a field invalid with a custom message; pass an empty string to clear it.
- `novalidate` on the form suppresses built-in submit validation but does not affect the Constraint Validation API on individual inputs.
