Chapter 13 of 26

Built-in Form Validation

Imagine an exam registration form where students submit an empty name, a mobile number with 7 digits, or an age of 250. Every bad submission wastes a round-trip to the server and frustrates the user, who only finds out about the mistake after the page reloads.

Modern HTML can catch most of these mistakes in the browser, before the form is sent, without a single line of JavaScript. You add a few attributes, and the browser blocks the submission and points at the problem field with a message.

In this chapter we'll learn those attributes, how the browser decides whether a field is valid, how to style valid and invalid fields, and how to customise messages with a little JavaScript.

What is Built-in Form Validation?

Built-in (constraint) validation is the browser's ability to check form controls against rules declared in HTML attributes – such as required, minlength, pattern, min and type – and to stop the form from submitting until all rules are satisfied.

The HTML standard calls these rules constraints, and the whole system the Constraint Validation API.

Here's the smallest possible example:

<form action="/subscribe" method="post">
  <label for="mail">Email</label>
  <input type="email" id="mail" name="email" required>
  <button type="submit">Subscribe</button>
</form>

If the user clicks Subscribe with the box empty, nothing is sent. Instead the browser focuses the box and shows a small pop-up message. In Chrome it says "Please fill out this field." If the user types abc, Chrome says "Please include an '@' in the email address. 'abc' is missing an '@'." (The exact wording differs between browsers and languages.)


Client-side vs Server-side Validation

Before learning the attributes, one rule you must never forget:

Browser validation is for the user's convenience, not for security. Anyone can turn it off, edit the HTML with developer tools, or send a request directly with tools like curl or Postman. The server must always validate everything again.

Point

Client-side (HTML/JS)

Server-side

Where it runs

User's browser

Your server

Speed of feedback

Instant

After a request

Can be bypassed

Yes, easily

No (it's your code)

Purpose

Better user experience, fewer bad requests

Data integrity and security

Can check against a database (e.g. "username taken")

Not by itself

Yes

Good websites do both.


The Validation Attributes

1. required

The field must not be empty.

<input type="text" name="fullname" required>

It works on text-like inputs, number and date/time inputs, <textarea>, <select>, check boxes, radio buttons and file inputs:

<!-- check box: must be ticked -->
<label><input type="checkbox" name="tnc" required> I accept the rules</label>

<!-- select: the first option has an empty value, so it counts as "nothing chosen" -->
<label for="state">State</label>
<select id="state" name="state" required>
  <option value="">-- choose --</option>
  <option>Kerala</option>
  <option>Punjab</option>
</select>

<!-- radio group: required on ANY one radio makes the whole group required -->
<fieldset>
  <legend>Category</legend>
  <label><input type="radio" name="cat" value="gen" required> General</label>
  <label><input type="radio" name="cat" value="obc"> OBC</label>
  <label><input type="radio" name="cat" value="sc"> SC/ST</label>
</fieldset>

Notice the <select> trick: a required select needs a first "placeholder" option with value="". Otherwise the first real option is selected by default and the field is never empty.

2. minlength and maxlength

<label for="u">Username (4 to 15 characters)</label>
<input type="text" id="u" name="username" minlength="4" maxlength="15" required>
  • maxlength stops the user typing beyond the limit, so the error rarely appears.

  • minlength shows an error on submit if the value is shorter (e.g. Chrome: "Please lengthen this text to 4 characters or more (you are currently using 2 characters).").

  • An empty field does not fail minlength – only required catches emptiness. That's why the two are usually used together.

  • Length rules are only checked for text the user typed. A value put there by HTML or JavaScript that is too short or too long is not flagged.

3. min, max and step

For number, range and the date/time types from the Input Types chapter:

<input type="number" name="age" min="17" max="25">
<input type="number" name="marks" min="0" max="100" step="0.5">
<input type="date" name="exam" min="2026-11-01" max="2026-12-31">

Typing 30 in the age box and submitting gives "Value must be less than or equal to 25." in Chrome. Typing 72.3 in marks fails step because allowed values are 0, 0.5, 1, 1.5 ... 100.

4. type itself

As we saw last chapter, email and url automatically check syntax. number and date types reject input the browser can't understand.

5. pattern

When no built-in type fits, describe the format with a regular expression:

<label for="pin">PIN code (6 digits)</label>
<input type="text" id="pin" name="pin" inputmode="numeric"
       pattern="[1-9][0-9]{5}" title="6-digit PIN code, not starting with 0" required>

Important details about pattern:

  • It must match the whole value. The browser behaves as if you had written ^(?: before and )$ after the pattern. So [0-9]{6} rejects 1234567 (7 digits) – you don't need ^ and $.

  • Don't put slashes around it: write [a-z]+, not /[a-z]+/.

  • It works only on text, search, tel, url, email and password inputs (not on <textarea> or number).

  • It's not checked when the field is empty – add required if the field is mandatory.

  • Browsers now compile the pattern with JavaScript's v (unicodeSets) flag. In practice this means some characters must be escaped even inside [ ]: for example a literal hyphen in a character class should be written \- ([A-Z0-9\-]), and literal ( ) [ { } / | need a backslash too. An invalid pattern is ignored – the field then accepts anything, and the only sign is a warning in the browser console.

  • The generic error is "Please match the requested format." Add a title describing the format; Chrome appends it to the message. Better still, show the format in visible text near the field.

Some handy patterns:

Need

Pattern

Matches

10-digit Indian mobile

[6-9][0-9]{9}

9876543210

PIN code

[1-9][0-9]{5}

560001

Username: letters, digits, underscore, 4–15 chars

\w{4,15}

ravi_21

PAN-style code (5 letters, 4 digits, 1 letter)

[A-Z]{5}[0-9]{4}[A-Z]

ABCDE1234F


How the Browser Decides: ValidityState

Every form control has a validity object with true/false flags. If any flag except valid is true, the control is invalid. Each flag maps to one attribute:

Flag

Becomes true when ...

Caused by

valueMissing

Required field is empty

required

typeMismatch

Value isn't a valid email/URL

type="email" / type="url"

patternMismatch

Value doesn't match the regex

pattern

tooShort / tooLong

User-typed text is outside the length limits

minlength / maxlength

rangeUnderflow / rangeOverflow

Value below min / above max

min / max

stepMismatch

Value not on an allowed step

step

badInput

Browser can't convert the input (e.g. half-typed date)

number, date types

customError

A custom message has been set

setCustomValidity()

valid

All the others are false

–

Fields that are never validated

Some controls are "barred" from validation – the browser skips them even if they have required:

  • disabled controls (they aren't submitted anyway).

  • readonly controls – so readonly required never blocks a form.

  • type="hidden" inputs.

  • Buttons of type button and reset.

We tested this in Chrome: an empty <input required readonly> reports willValidate = false and valid = true.


Worked Example: Is This Form Valid?

<form action="/join" method="post">
  <input type="text" name="name" value="Al" minlength="3" required>
  <input type="text" name="pin" value="" pattern="[0-9]{6}">
  <input type="number" name="age" value="15" min="16">
  <input type="email" name="email" value="al@college" required>
  <input type="text" name="roll" value="" readonly required>
  <button type="submit">Join</button>
</form>

The page has just loaded and the user clicks Join without typing anything. Let's check each field:

  1. name = "Al", minlength 3 → too short, but the value came from the HTML, not from the user's typing, so tooShort is not raised. Valid. (If the user had typed "Al" it would be invalid.)

  2. pin = empty, pattern set, not required → pattern is not checked on empty values. Valid.

  3. age = 15, min 16 → rangeUnderflow. Invalid.

  4. email = "al@college" → has text before and after @, which is enough for the browser. Valid.

  5. roll = empty, required, but readonly → barred from validation. Valid.

Result: the form is blocked by exactly one field, age, and Chrome shows "Value must be greater than or equal to 16." next to it. This is a favourite tricky question because three of the five "obvious" errors are not errors at all.


Turning Validation Off: novalidate and formnovalidate

Sometimes you want to skip the checks – for example, a "Save draft" button on a long application form, or when you want to show your own JavaScript-based messages.

<!-- Whole form: never validate on submit -->
<form action="/apply" method="post" novalidate>
  ...
</form>

<!-- One button skips validation, the other doesn't -->
<form action="/apply" method="post">
  <input type="text" name="sop" required>
  <button type="submit">Submit application</button>
  <button type="submit" formnovalidate formaction="/draft">Save draft</button>
</form>

With novalidate, the rules still exist – the validity object and the CSS pseudo-classes below still work – the browser just doesn't block submission or show its bubbles.


Styling Valid and Invalid Fields with CSS

Browsers expose the validation state through CSS pseudo-classes, so you can colour fields without JavaScript:

Pseudo-class

Matches

:valid / :invalid

Field currently passes / fails its constraints (also works on <form> and <fieldset>)

:user-valid / :user-invalid

Same, but only after the user has interacted with the field or tried to submit

:required / :optional

Field has / doesn't have required

:in-range / :out-of-range

Value inside / outside min–max

:placeholder-shown

Field is empty and showing its placeholder

Here is why :user-invalid matters:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Validation styles</title>
  <style>
    .early input:invalid      { border: 2px solid crimson; }
    .polite input:user-invalid { border: 2px solid crimson; }
    input:user-valid           { border: 2px solid seagreen; }
  </style>
</head>
<body>
  <form class="early" action="/a">
    <p>Using :invalid</p>
    <label for="n1">Name</label> <input type="text" id="n1" name="n" required>
    <button type="submit">Send</button>
  </form>
  <form class="polite" action="/b">
    <p>Using :user-invalid</p>
    <label for="n2">Name</label> <input type="text" id="n2" name="n" required>
    <button type="submit">Send</button>
  </form>
</body>
</html>

When this page first loads, the first Name box already has a red border – the user hasn't typed anything yet, but an empty required field is invalid, so :invalid matches immediately. That feels like being scolded before you start. The second box looks normal and only turns red after the user has typed something invalid and left the field, or tried to submit. It turns green once the value is acceptable.

:user-invalid and :user-valid have worked in all major browsers since late 2023, so prefer them for error styling.


Custom Messages with the Constraint Validation API

Some rules can't be expressed in attributes – "confirm password must match password", for example. For these, a few lines of JavaScript plug into the same built-in system. (If you haven't learnt JavaScript yet, read this section for the idea; the HTML attributes above already cover most needs.)

The key methods and properties on every form control:

Member

What it does

checkValidity()

Returns true/false; if false, fires an invalid event. No message is shown.

reportValidity()

Like checkValidity() but also shows the browser's message bubble

setCustomValidity(msg)

Non-empty msg marks the field invalid with that message; "" clears it

validity

The ValidityState object from the table above

validationMessage

The message the browser would show

willValidate

false if the control is barred from validation

checkValidity() and reportValidity() also exist on the <form> element, where they check every control at once.

Example: confirm password

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Sign up</title>
</head>
<body>
  <form action="/signup" method="post">
    <p>
      <label for="pw">Password (min 8 characters)</label>
      <input type="password" id="pw" name="password" minlength="8" required
             autocomplete="new-password">
    </p>
    <p>
      <label for="pw2">Confirm password</label>
      <input type="password" id="pw2" name="confirm" required
             autocomplete="new-password">
    </p>
    <button type="submit">Create account</button>
  </form>

  <script>
    const pw = document.getElementById("pw");
    const pw2 = document.getElementById("pw2");

    function checkMatch() {
      if (pw2.value !== pw.value) {
        pw2.setCustomValidity("Passwords do not match.");
      } else {
        pw2.setCustomValidity("");   // IMPORTANT: clear the error
      }
    }

    pw.addEventListener("input", checkMatch);
    pw2.addEventListener("input", checkMatch);
  </script>
</body>
</html>

How it works, step by step:

  1. Every time either box changes, checkMatch() runs.

  2. If the values differ, setCustomValidity("Passwords do not match.") sets validity.customError to true, so the field becomes :invalid.

  3. When the user clicks Create account, the browser's normal validation sees the invalid field, blocks submission and shows "Passwords do not match." in its bubble.

  4. When the values match, setCustomValidity("") clears the error.

Step 4 is where most bugs come from. A custom error stays until you clear it with an empty string. We checked this in Chrome: after setCustomValidity("Custom!"), typing a perfectly good value still leaves the field invalid with customError: true until setCustomValidity("") is called.


When Does Validation Run?

User clicks a submit button (or presses Enter)
        ↓
Is the form "novalidate" or the button "formnovalidate"?
   yes → submit immediately
   no  ↓
Check every control that "will validate"
        ↓
All valid?  yes → submit
            no  → fire "invalid" event on each bad control,
                  focus the first one, show its message,
                  DO NOT submit

Validation does not run when the form is submitted from JavaScript with form.submit(). If you submit from script, use form.requestSubmit() instead, which behaves like clicking a submit button (validation included).


Common Mistakes

  • Treating HTML validation as security. It can be bypassed in seconds. Always validate on the server.

  • minlength or pattern without required. Empty values skip those checks, so an empty field passes.

  • Adding ^ and $ or slashes to pattern. Anchors are implied; slashes become literal characters to match.

  • Unescaped hyphen in a character class like [A-Z0-9-] – invalid under the v flag, so the pattern is silently ignored. Write [A-Z0-9\-].

  • Forgetting setCustomValidity(""). The field stays invalid forever.

  • A required <select> without an empty first option. It can never be empty, so required does nothing.

  • Expecting readonly fields to be validated. They are skipped.

  • Styling with :invalid and showing red boxes before the user has typed anything. Use :user-invalid.


Interview Questions

1. Why do we need server-side validation if HTML can validate?

Client-side checks can be disabled or bypassed (edit the HTML, use novalidate, or send requests directly). They exist for user experience. The server must validate every input to protect data and security.

2. Does pattern="[0-9]{6}" accept "1234567"?

No. The pattern must match the entire value (it is implicitly anchored with ^(?: and )$), and 7 digits is not exactly 6.

3. An input has minlength="5" but no required. Can the form be submitted with it empty?

Yes. Length and pattern constraints are not checked on empty values. Add required to forbid emptiness.

4. Difference between checkValidity() and reportValidity()?

Both return true/false and fire invalid events on failure. reportValidity() additionally shows the browser's error message to the user.

5. What is the difference between :invalid and :user-invalid?

:invalid matches whenever the value fails constraints, even on page load. :user-invalid matches only after the user has interacted with the field or attempted to submit, which gives friendlier error styling.

6. Which of these are validated: a disabled required field, a readonly required field, a hidden required input?

None of them. Disabled, readonly and hidden controls are barred from constraint validation.

7. How do you allow a "Save draft" button to bypass validation?

Add formnovalidate to that submit button. The other submit buttons still validate normally.


Conclusion

HTML can check user input before submission using simple attributes, saving the user and the server from bad data.

required             → must not be empty
minlength/maxlength  → length limits (user-typed text)
min/max/step         → numbers and dates
type=email/url       → syntax checks
pattern              → full-value regex (v flag)
novalidate / formnovalidate → skip checks
:user-invalid        → style errors after interaction
setCustomValidity()  → your own rules and messages
  • Constraints are checked when the user submits; the first invalid field gets focus and a message.

  • Empty optional fields skip pattern and length checks.

  • Disabled, readonly and hidden fields are not validated.

  • Client-side validation improves experience; server-side validation provides safety.

With forms complete, the next chapter, Semantic HTML, steps back to the page as a whole and shows how to describe its structure – header, navigation, main content, articles and footer – with meaningful elements.