Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 9.6 — Form Events and Validation in JavaScript
JavaScript · Example 3 of 4

A custom rule with setCustomValidity

checkValidity() fires invalid on each bad field before returning false. Try typing different passwords yourself and pressing the button: the browser shows your message in its bubble.

input fires on every change to a field's value, change fires when a change is committed, and submit fires on the form; FormData collects every named field in one step, and the Constraint Validation API (checkValidity, setCustomValidity, validity) lets JavaScript add its own rules and messages to the browser's built-in ones.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Make a <textarea id="bio" maxlength="160"> with a #left paragraph that shows how many characters are left, updated as the user types. Test by setting a value and dispatching input.

02

Write a submit handler for a form with fields title and tags (several checkboxes) that logs { title, tags }, with tags as an array.

Explain it without notes

01

What is the difference between the input and change events?

02

How does FormData decide which fields to include?

03

How do you add a custom validation rule, and what's the common mistake?

04

Why validate on the client if you must validate on the server anyway?

A custom rule with setCustomValidity

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

invalid: confirm | customError: true | Passwords don't match
valid? false
valid now? true
submitted!