Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 87 ยท Forms and User Input

Form Validation

Validate Vue 3 forms without a library - computed error messages, touched and dirty state, async username checks that ignore stale answers, and a reusable validator composable.

Validation answers a simple question: is what the user typed acceptable? The hard part is not the rules. It is deciding when to show a message, where to put it, and how to keep the logic from turning into a tangle of flags. Vue gives you a clean way to do it, because validation is a calculation on state, and calculations are what computed is for.

This lesson builds validation by hand in three steps: rules as a computed object, "touched" state that controls when messages appear, and finally a small reusable useForm function. Along the way you will handle a check that needs a server (is this username free?). If you have not yet built a basic form, read building forms first.

Client-side validation is a convenience for the user, not a security measure. Anyone can send requests without your page. The server must validate everything again, and its answers (for example "that email is already registered") should be shown in the same place as your own messages.

Errors are derived state

Do not store a list of errors and try to update it from every handler. Compute it from the values. Whenever a value changes, the computed object is recalculated, and the template that reads it updates. There is nothing to "clear".

JavaScript
const errors = computed(() => {
  const result = {};
  if (form.username.length < 3) result.username = "Use at least 3 characters.";
  if (!/^\S+@\S+\.\S+$/.test(form.email)) result.email = "Enter a valid email address.";
  return result;
});
const isValid = computed(() => Object.keys(errors.value).length === 0);

Each key exists only while the field is invalid. isValid is true when the object is empty, so a submit button, a progress hint or a summary can all read it.

Touched state: when to show messages

If you show every message immediately, a user sees "Enter a valid email" before typing a single character. That feels like being scolded. The usual compromise is to track which fields the user has touched (left at least once, with the blur event) and show an error only for those. When the form is submitted, mark everything as touched so all remaining problems appear at once.

A related idea is dirty state: has anything changed from the starting values? It is useful for "Unsaved changes" hints and for enabling a Save button only when there is something to save.

Computed errors, touched fields and a dirty flag

Press Sign up with nothing typed: all three messages appear at once, because submit touches every field. Then fix the username and click out of it: its message disappears the moment the value becomes valid, without any "clear error" code. The small line at the bottom shows that isValid and isDirty are plain computed values.

Three details are worth copying:

  • novalidate on the form stops the browser from showing its own bubbles on top of yours.
  • :aria-invalid and aria-describedby tell assistive technology which field is wrong and where the message is. The message element is always in the page (it just contains no text when valid), so the link stays stable.
  • shownError(field) combines the two ideas: an error is visible only when it exists and the field was touched.
flowchart LR
  V["form values"] --> R["rules in computed"]
  R --> E["errors object"]
  T["touched flags (blur, submit)"] --> S["shownError(field)"]
  E --> S
  S --> U["Message in the template"]
  E --> I["isValid"]
  I --> B["Submit allowed or blocked"]

Rules turn values into errors; touched flags decide which errors the user gets to see; isValid gates the submit.

Choosing the timing

There is no single right moment. Most forms mix these:

When Good for Risk
On submit only Short forms, simple sign-ups Users find all errors at the end
On blur (touched) Most fields Slight delay before feedback
On every keystroke Password strength, character counters Nags before the user has finished
"Reward early, punish late" Show an error on blur, but hide it on the first keystroke that fixes it Slightly more code

The last row is what the example above does without extra work: touched stays true after the first blur, and the computed error vanishes as soon as the value is valid.

Async validation: asking the server

Some rules cannot be checked in the browser, such as "is this username free?". The check takes time and can fail, so the field needs a small state machine: idle, checking, available or taken.

The tricky part is stale answers. If the user types ada, then quickly adam, the server may answer for adam first and for ada second. If you just save whatever arrives last, the screen shows a result for text that is no longer in the box. The standard cure is a counter: every new check gets the next number, and when an answer comes back you ignore it unless it is still the newest one. A watcher is the right tool to start the check whenever the value changes.

In real code you would also debounce (wait until typing pauses) so a request is not sent per keystroke; composable patterns shows a useDebounce. The demo fakes a server in the browser: the names admin, ada and root are taken, and short names answer slowly on purpose, so you can provoke an out-of-order answer.

Async username check that ignores stale answers

Type ada, then immediately add an m. The three-letter name takes 700 ms, the four-letter one only 250 ms, so the answer for adam arrives first and the late answer for ada is ignored (it is listed under the field). Without the id !== latest guard, the final text would say "Already taken" for adam, which is wrong. This is the same race-condition problem you will meet in fetching data.

Whatever you do, treat async validity as part of isValid: a form should not submit while the state is checking or taken.

A reusable validator: useForm

Once you have written the same touched flags and error lookups three times, extract them. A function that starts with use and returns reactive state is a composable. This one takes the starting values and a table of rules. A rule is just a function that returns an error message, or an empty string when the value is fine.

A plain-Vue useForm composable with rules

Look at what the component had to write: a list of fields, a table of rules, and two tiny functions. Everything else is inside useForm. Rules stop at the first message for each field (break), so the user sees one problem at a time: "Password is required." first, then "Use at least 8 characters." The sameAs rule receives all values as a second argument, which is how one field can depend on another.

Two details deserve attention. useForm returns isValid as a computed ref, and because the component returns it from setup the template can use it unwrapped, while script code reads form.isValid.value (see ref for unwrapping). And the component spreads ...form into its return value; because values is reactive and the others are refs or functions, that is safe.

Libraries such as VeeValidate, FormKit and Vuelidate, or schema validators such as Zod, cover bigger needs (nested objects, arrays of rows, shared schemas between client and server). They are not available in this sandbox, but they follow the same model: values in, errors out, touched state decides visibility. Understanding the hand-built version makes them easy to learn.

Writing helpful messages

  • Say what to do, not just what is wrong: "Use at least 8 characters" beats "Invalid password".
  • Show one message per field at a time.
  • Keep the message next to its field and connect it with aria-describedby; for a long form add a summary at the top that links to each invalid field.
  • Never clear the user's input when something is wrong.
  • Keep the values you validate in a normal, trimmed form (v-model.trim, see v-model).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where should the object of validation errors usually live?

    Errors are a function of the values, so a computed property keeps them in sync automatically and there is no clearing logic to write.
  2. 2. What is the purpose of touched flags?

    Rules can be evaluated all the time, but showing every message at once is unfriendly. Touched (set on blur or submit) controls visibility only.
  3. 3. A user types 'ada' and then 'adam'. The answer for 'ada' arrives last. How do you avoid showing a wrong result?

    Responses can arrive out of order. Comparing the id of the finished check with the newest id lets you throw away stale answers.
  4. 4. Why does the example add novalidate to the form?

    With novalidate the browser skips its constraint-validation UI, so only your own messages (with aria-describedby) are shown.
  5. 5. Is client-side validation enough to protect your data?

    Client-side checks improve the experience but can be bypassed. The server is the only place where validation can be trusted.

Summary

  • Derive errors with computed from the form values; never maintain an errors list by hand.
  • Use touched flags (set on blur and on submit) to decide when a message is visible, and a dirty flag to detect unsaved changes.
  • Use novalidate, :aria-invalid and aria-describedby so your own messages replace the browser's and stay accessible.
  • Async checks need a state (idle, checking, available, taken) and a guard against stale answers; debounce real requests.
  • Extract repeated logic into a useForm(initial, rules) composable where a rule is a function returning a message or an empty string.
  • The server must validate again; client validation is for the user's benefit.

Next: Components Basics