Vue 3 Typed Form Validation

Build type-safe reactive forms in Vue 3 with TypeScript using composable validators, computed error states, and debounced field validation that prevents.

TypescriptVueForm Validation

Code

snippet
import { ref, computed, type Ref } from 'vue';

interface Rules<T> {
  [K in keyof T]?: (v: T[K]) => string | true;
}

export function useTypedForm<T extends Record<string, string>>(
  init: T,
  rules: Rules<T>,
) {
  const values = ref(init) as Ref<T>;
  const errors = computed(() => {
    const e: Partial<Record<keyof T, string>> = {};
    for (const key in rules) {
      const result = rules[key]?.(values.value[key]);
      if (result !== true && result !== undefined) e[key] = result;
    }
    return e;
  });
  const isValid = computed(() => Object.keys(errors.value).length === 0);
  return { values, errors, isValid };
}

What the code does

Repetition is confined to for (const key in rules) — the rest of the file is straight-line. The snippet’s external surface is ref, computed, type Ref, all of it via vue.

The result comes back as an object carrying values, errors.

Watch out for

  • Plan for an install step: vue is a real dependency, resolved by the package manager.

Applying it

useTypedForm is what another module would consume; nothing else here is load-bearing for callers.

The call returns values, errors — destructure what you need at the call site.

Statements that matter

[K in keyof T]?: (v: T[K]) => string | true;
const isValid = computed(() => Object.keys(errors.value).length === 0);
const result = rules[key]?.(values.value[key]);

Interactive Tools for This Topic

FAQ

Does `useTypedForm` modify its input?
No mutation happens — the function reads its input and returns a new value.
Does this require external packages?
Yes — `vue`. Add it to your project before running the snippet.