How-To Guide

How to Build Vue 3 Reactive Forms

Build a typed Vue 3 form composable with reactive values, computed validation, touched fields, async submit state, server errors, and Vitest coverage.

On this page

  1. Introduction
  2. Create the composable
  3. Use the composable in a component
  4. Validate at the right time
  5. Handle async validation with watcher cleanup
  6. Handle server errors
  7. Test the composable and the component
  8. Common pitfalls
  9. Conclusion

Introduction

Vue’s reactivity system is a natural fit for forms. A field changes, a computed error recalculates, and the template updates without manual subscriptions. The Composition API makes that logic reusable through a composable, which is Vue’s equivalent of a custom hook.

The difficulty is not making a value reactive; it is deciding when validation runs, how touched and submitted state interact, and how to avoid the reactivity traps that make a form appear broken. This tutorial builds a typed useForm composable with pure validators, computed errors, touched fields, submission state, server errors, and a debounced async check. It also covers the Vue-specific mistakes that cause a computed value to stop updating.

Create the composable

Start with shared types. A validator receives the current field value and all values, and returns a message or undefined. Keeping rules outside the component makes them testable without mounting anything:

// useForm.ts
import { computed, reactive, ref } from 'vue';

type Validator<T> = (value: string, values: T) => string | undefined;
export type Rules<T> = Partial<Record<keyof T, Validator<T>[]>>;

export function useForm<T extends Record<string, string>>(
  initialValues: T,
  rules: Rules<T>
) {
  const values = reactive({ ...initialValues }) as T;
  const touched = reactive<Partial<Record<keyof T, boolean>>>({});
  const submitted = ref(false);
  const submitting = ref(false);
  const serverError = ref<string | null>(null);
  const serverErrors = reactive<Partial<Record<keyof T, string>>>({});

  function validateField(name: keyof T): string | undefined {
    for (const rule of rules[name] ?? []) {
      const message = rule(values[name], values);
      if (message) return message;
    }
    return undefined;
  }

  const errors = computed(() => {
    const result: Partial<Record<keyof T, string>> = {};
    for (const name of Object.keys(values) as (keyof T)[]) {
      if (!submitted.value && !touched[name]) continue;
      const message = validateField(name);
      if (message) result[name] = message;
      else if (serverErrors[name]) result[name] = serverErrors[name];
    }
    return result;
  });

  const isValid = computed(() =>
    (Object.keys(values) as (keyof T)[]).every((name) => !validateField(name))
  );

  async function handleSubmit(
    onValid: (values: T) => Promise<void>,
    onError?: (error: unknown) => boolean
  ): Promise<boolean> {
    submitted.value = true;
    serverError.value = null;

    if (!isValid.value) return false;

    submitting.value = true;
    try {
      await onValid({ ...values });
      return true;
    } catch (error) {
      const handled = onError?.(error) ?? false;
      if (!handled) {
        serverError.value =
          error instanceof Error ? error.message : 'Submit failed';
      }
      return false;
    } finally {
      submitting.value = false;
    }
  }

  function setServerErrors(
    fieldErrors: Partial<Record<keyof T, string>>
  ): void {
    for (const name of Object.keys(fieldErrors) as (keyof T)[]) {
      serverErrors[name] = fieldErrors[name];
      touched[name] = true;
    }
  }

  function clearServerError(name: keyof T): void {
    delete serverErrors[name];
  }

  function reset(): void {
    Object.assign(values, initialValues);
    for (const key of Object.keys(touched)) delete touched[key];
    for (const key of Object.keys(serverErrors)) delete serverErrors[key as keyof T];
    submitted.value = false;
    serverError.value = null;
  }

  return {
    values,
    touched,
    errors,
    isValid,
    submitting,
    serverError,
    setServerErrors,
    clearServerError,
    validateField,
    handleSubmit,
    reset,
  };
}

values is reactive, so reading values[name] inside errors and isValid registers a dependency. When a field changes, both computeds invalidate. errors hides messages for untouched fields until the user blurs them or submits, while isValid always checks every field. That separation prevents an empty form from showing a wall of errors on first render.

submitted and submitting are refs because they hold primitive values. touched is a reactive object because it is a map of field names. Mixing the two is intentional: use ref for a single value, reactive for a keyed collection.

Use the composable in a component

Define rules outside the component and destructure the returned refs:

<script setup lang="ts">
import { useForm, type Rules } from './useForm';

type LoginValues = { email: string; password: string };

const rules: Rules<LoginValues> = {
  email: [
    (value) => (value.trim() ? undefined : 'Email is required'),
    (value) =>
      /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(value)
        ? undefined
        : 'Enter a valid email address',
  ],
  password: [
    (value) => (value.length >= 8 ? undefined : 'Use at least 8 characters'),
  ],
};

const {
  values,
  touched,
  errors,
  submitting,
  serverError,
  setServerErrors,
  clearServerError,
  handleSubmit,
} = useForm<LoginValues>({ email: '', password: '' }, rules);

class ApiError extends Error {
  constructor(
    public readonly fieldErrors: Partial<Record<keyof LoginValues, string>>
  ) {
    super('Validation failed');
  }
}

async function submit() {
  await handleSubmit(
    async (formValues) => {
      await api.login(formValues);
    },
    (error) => {
      if (error instanceof ApiError) {
        setServerErrors(error.fieldErrors);
        return true;
      }
      return false;
    }
  );
}
</script>

<template>
  <form novalidate @submit.prevent="submit">
    <label for="email">Email</label>
    <input
      id="email"
      v-model="values.email"
      name="email"
      type="email"
      autocomplete="email"
      :aria-invalid="errors.email ? 'true' : undefined"
      :aria-describedby="errors.email ? 'email-error' : undefined"
      @input="clearServerError('email')"
      @blur="touched.email = true"
    />
    <p v-if="errors.email" id="email-error" role="alert">
      {{ errors.email }}
    </p>

    <label for="password">Password</label>
    <input
      id="password"
      v-model="values.password"
      name="password"
      type="password"
      autocomplete="current-password"
      :aria-invalid="errors.password ? 'true' : undefined"
      :aria-describedby="errors.password ? 'password-error' : undefined"
      @input="clearServerError('password')"
      @blur="touched.password = true"
    />
    <p v-if="errors.password" id="password-error" role="alert">
      {{ errors.password }}
    </p>

    <p v-if="serverError" role="alert">{{ serverError }}</p>

    <button type="submit" :disabled="submitting">
      {{ submitting ? 'Signing in…' : 'Sign in' }}
    </button>
  </form>
</template>

Destructuring the returned refs is safe because they are refs, not properties of a reactive object. Destructuring values itself would be a mistake: const { email } = values captures a plain string and stops updating. If a child component needs individual fields, use toRefs(values) or pass the reactive object.

The template auto-unwraps top-level refs such as errors, submitting, and serverError. Inside <script>, they require .value. Forgetting .value in a function is one of the most common Composition API bugs; TypeScript catches many of these cases when the ref type is known.

Validate at the right time

The composable validates a field on blur through touched, and revalidates it on change because errors depends on values. That gives immediate feedback after the user has interacted with a field without showing errors before they begin.

If you want to validate only on submit and clear errors as the user edits, track a submitted flag and skip touched-field validation until submission. Do not mix both strategies without a clear rule; users notice when one field validates on blur and another only after submit.

Rule functions should be pure. Do not perform network requests, read global state, or mutate values inside a rule. A rule that trims a value changes the data the user submitted; normalize explicitly in a separate function and document it. For a password, do not trim at all; spaces may be intentional.

Handle async validation with watcher cleanup

Username availability is asynchronous. Use watch with an abort controller and a debounce timer. Vue’s onCleanup callback runs before the next watcher execution and when the component unmounts:

import { ref, watch } from 'vue';

function useAvailability(username: () => string) {
  const status = ref<'idle' | 'checking' | 'available' | 'taken'>('idle');

  watch(
    username,
    async (name, _previous, onCleanup) => {
      if (name.length < 3) {
        status.value = 'idle';
        return;
      }

      const controller = new AbortController();
      const timer = window.setTimeout(async () => {
        status.value = 'checking';
        try {
          const response = await fetch(
            `/api/username?name=${encodeURIComponent(name)}`,
            { signal: controller.signal }
          );
          status.value = response.ok ? 'available' : 'taken';
        } catch {
          if (!controller.signal.aborted) status.value = 'idle';
        }
      }, 300);

      onCleanup(() => {
        window.clearTimeout(timer);
        controller.abort();
      });
    },
    { flush: 'post' }
  );

  return status;
}

The watcher source is a getter, not a static string, so it reacts to the current value. Cleanup cancels both the timer and the request. Without cleanup, an older response can arrive after a newer one and overwrite the status with stale information. The server must still enforce uniqueness when the record is written; availability is advisory.

Handle server errors

Client validation cannot know whether an email is already registered. Return field-level errors from the server and pass them to setServerErrors:

await handleSubmit(
  (formValues) => api.login(formValues),
  (error) => {
    if (error instanceof ApiError) {
      setServerErrors(error.fieldErrors);
      return true;
    }
    return false;
  }
);

setServerErrors writes into a separate reactive serverErrors map and marks the affected fields touched. The errors computed merges a server message only when the client rule passes for that field, so a stale server error does not hide a new client-side problem. Editing a field calls clearServerError, which removes the old server message until the next submit. Keep server messages separate from client messages so a server release can change copy without changing the rules. Do not assign to errors.value; a computed is read-only unless it defines a setter. The onError callback returns true when it has handled the error, which prevents handleSubmit from also setting the general serverError message.

Do not display a raw exception from the server. Map known error codes to product copy and log the details with a request id. A generic “Could not sign in” is safer than leaking whether an account exists, unless the product intentionally supports account discovery.

Test the composable and the component

Test rules and the composable directly, then mount the component for integration behavior:

import { mount } from '@vue/test-utils';
import { nextTick } from 'vue';
import LoginForm from './LoginForm.vue';

test('shows an email error after submit', async () => {
  const wrapper = mount(LoginForm);
  await wrapper.find('form').trigger('submit');
  await nextTick();

  expect(wrapper.find('#email-error').text()).toBe('Email is required');
  expect(wrapper.find('input[name="email"]').attributes('aria-invalid')).toBe('true');
});

Add a test that typing a valid email clears the error after the field is touched, and a test that submitting disables the button while the promise is pending. For async availability, use fake timers and a mocked fetch; assert that an obsolete response is ignored after the input changes.

@vue/test-utils mounts the component without a browser, but it does not exercise real focus or styles. Use Playwright for the full keyboard and screen-reader-oriented flow when those behaviors matter.

Common pitfalls

  • Destructuring a reactive object. Reactivity is lost; use refs or toRefs.
  • Missing .value in script. Refs are not unwrapped outside templates.
  • A computed with a side effect. Validation should read state, not mutate it.
  • Validating every field on first render. Gate messages on touched or submitted.
  • No cleanup for async checks. Stale responses overwrite current state.
  • Assigning to a computed. Computeds are read-only unless they define a setter.
  • Trusting client rules. Repeat validation and uniqueness checks on the server.
  • Using array index as a key in repeated fields. Reordering fields corrupts input state.

Conclusion

A Vue 3 form composable is a small reactive state machine: values, touched fields, computed errors, and submission status. Keep rules pure, expose refs rather than raw reactive properties, validate on blur and submit, and cancel async work when inputs change. The Composition API removes the need for a heavy form library on focused forms, while leaving the door open to VeeValidate or a schema library when nested arrays and cross-field rules become complex.

Sources: Vue 3 reactivity fundamentals, Vue computed, Vue watchers and cleanup.

FAQ

Should I use reactive or ref for form values?
Use reactive for an object of fields when the shape is stable, and computed for derived errors. If you need to pass individual fields around, return refs or use toRefs. Destructuring a reactive object directly loses reactivity.
Why does my computed error not update?
The computed did not read the reactive value it depends on, or the value was destructured and lost its proxy. Read values inside the computed, and destructure the refs returned by the composable rather than destructuring the reactive values object.
Should validation run on every input event?
Usually validate on submit and on blur, then revalidate a touched field as the user types. Continuous validation from the first keystroke produces premature errors and a noisy screen-reader experience.

Related Examples

Interactive Tools for This Topic