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.
Code
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:
vueis 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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.