Composables
useForm
Description
The useForm composable provides a type-safe, reactive, and schema-driven form handler for Vue 3 applications using the Composition API. It integrates zod for validation, enabling powerful runtime type-checking and error handling. Designed to improve form usability and maintainability, this utility includes field-level and form-level validation, auto-watching for reactive validation, and streamlined submission workflows.
FEATURE GOALS
- Enable reactive form state and error tracking using zod schemas.
- Provide field and full-form validation functions.
- Allow programmatic and reactive submission handling.
- Support initial values, form reset, and optional auto-validation on change.
FEATURE EXPECTATIONS
- Automatically validates form fields if watch and immediate options are enabled.
- Returns validation errors in a structured format.
- Prevents submission when form is invalid.
- Returns a pending state while awaiting async submission methods.
- Provides a simple API for use across Vue components.
DEV STRATEGIES
- Composables Logic
const {
formFields,
errors,
isValid,
onSubmit,
reset,
validateForm,
validateFormField,
} = useForm({
validationSchema: myZodSchema,
initialFormValue: { name: "", email: "" },
watch: true,
immediate: true,
});
- Submission
const submit = onSubmit(async (data) => {
await apiCallToSubmit(data);
});
- Validates the form before submission.
- Tracks pending state (pending) during async operation.
- Resets errors after successful validation or submission.
- COMPOSABLE STRUCTURE
useForm<T extends ZodSchema>(options: UseFormOptions<T>): UseFormReturn<T>
- DEFAULT BEHAVIOR
| Feature | Default | Description |
|---|---|---|
initialFormValue | {} | Used to initialize the form fields. |
watch | false | If enabled, watches fields and runs validation on each change. |
immediate | false | If enabled, runs validation immediately on component mount. |
errors[field] | null | Errors are cleared on reset or successful validation. |
isValid | Computed from errors | Returns true if all fields have no validation errors. |
- ERROR RESPONSE STRUCTURE
- Validation errors are structured per field, with an
optionalcause:
errors = {
email: { message: "Invalid email format" },
password: null,
};
- Errors are automatically cleared on successful validation or when the
reset()method is called.
FLOW SUMMARY
- Initializes reactive
formFieldsanderrorsusing thezodschema and provided values. - Validates on-demand or via
watch()depending on options. - Provides
onSubmit()to handle validated submissions with built-in async support. - Errors and form state are fully reactive and easily integrated into templates.
- Offers
reset()to restore initial form state.