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

  1. Composables Logic
const {
  formFields,
  errors,
  isValid,
  onSubmit,
  reset,
  validateForm,
  validateFormField,
} = useForm({
  validationSchema: myZodSchema,
  initialFormValue: { name: "", email: "" },
  watch: true,
  immediate: true,
});
  1. 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.
  1. COMPOSABLE STRUCTURE
useForm<T extends ZodSchema>(options: UseFormOptions<T>): UseFormReturn<T>
  1. DEFAULT BEHAVIOR
FeatureDefaultDescription
initialFormValue{}Used to initialize the form fields.
watchfalseIf enabled, watches fields and runs validation on each change.
immediatefalseIf enabled, runs validation immediately on component mount.
errors[field]nullErrors are cleared on reset or successful validation.
isValidComputed from errorsReturns true if all fields have no validation errors.

  1. ERROR RESPONSE STRUCTURE
  • Validation errors are structured per field, with an optional cause:
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 formFields and errors using the zod schema 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.

Copyright © 2026