Performance:
Form validation runs deeply on every value change. To keep things snappy, optimize your validation schema and rules.
useFormik Composable The useFormik composable is your ultimate ally for managing complex forms in Vue 3 applications. With its simplicity and efficiency, it provides:
With useFormik, you can effortlessly create dynamic, user-friendly forms that deliver a robust and consistent user experience.
Form validation runs deeply on every value change. To keep things snappy, optimize your validation schema and rules.
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| initialValues | T | true | - | An object containing the initial values for the form fields. |
| validateOnMount | boolean | false | true | If true, performs validation when the form is initialized. |
| validateOnChange | boolean | false | true | If true, performs validation when form fields change. |
| validateOnBlur | boolean | false | true | If true, performs validation when form fields lose focus. |
| validationDebounce | number | false | 0 | Debounce time in milliseconds for validation when validateOnChange is true. |
| preventDefault | boolean | false | true | If true, prevents the default form submission behavior. |
| onSubmit | FormikOnSubmit<T> | false | - | A function to handle form submission. It receives the current form values and helpers and may return a Promise for async workflows. |
| yupSchema | ObjectSchema<T> | false | - | A yup schema for validating the form fields. |
| joiSchema | ObjectSchema<T> | false | - | A joi schema for validating the form fields. |
| zodSchema | ZodType<T> | false | - | A zod schema for validating the form fields. |
| structSchema | Struct<T> | false | - | A superstruct schema for validating the form fields. |
| validationSchema | FormikValidationSchema<T> | false | - | A custom validation rules object or function for validating the form fields. Supports synchronous or asynchronous rules. |
| initialErrors | Partial<Record<keyof T, unknown>> | false | - | Initial error values for form fields. |
| initialTouched | Partial<Record<keyof T, unknown>> | false | - | Initial touched state values for form fields. |
π Notes:
The validation schema can be supplied as
yupSchema,joiSchema,zodSchema,structSchema, orvalidationSchemaparameters.If any of the schema parameters are not provided, the form will not perform any validation.
Please use Object schemas for
YupandJoiand not thestringschemas.Custom validation rules and schema adapters may return promises; the form will await their resolution before updating errors.
onSubmit handlerTYPE: (FormikOnSubmit<T> = values: T, helpers: FormikHelpers<T>)
When the onSubmit function is invoked by the submit handler, it receives two arguments: values and helpers.
The values argument is an object that contains the current values of the form fields.
The helpers argument is an object that contains a set of utility functions that can be used to interact with the form state.
reset - Resets the form to its initial state.setErrors - Sets the errors for the form fields.setValues - Sets the values for the form fields. Accepts an optional { replace?: boolean } parameter to fully replace the current values. setSubmitting - Sets the submitting state of the form.setTouched - Sets the touched state of the form fields.setFieldValue - Sets the value of a specific form field.setFieldTouched - Sets the touched state of a specific form field.event - The event that triggered the form submission or reset.| Property | Type | Description |
|---|---|---|
| values | reactive<T> | Reactive object containing the current values of form fields. |
| errors | reactive<object> | Reactive object containing field-level validation errors. |
| touched | reactive<object> | Reactive object indicating whether a field has been interacted with. |
| isValid | computed<boolean> | Computed property indicating if the form is valid. |
| isDirty | computed<boolean> | Computed property indicating if the form values have changed from the initial values. |
| isSubmitting | ref<boolean> | Ref indicating if the form is in the submitting state. Automatically resets after validation failures or when async submits resolve. |
| isValidating | ref<boolean> | Ref indicating if the form is in the validating state. |
| submitCount | ref<number> | Ref containing the number of form submission attempts. |
| fieldHandlers | computed<object> | Handlers (onBlur and onChange) for form fields. |
π Notes:
- Reactivity: Values, errors, and touched objects are fully reactive, enabling two-way data binding with form fields.
- Computed properties:
isValid&isDirtyare computed properties. Don't forget to use.valuewhile accessing it inside the template.
| Method | Parameters | Description |
|---|---|---|
| setValues | (newValues: Partial<T>, options?: { replace?: boolean }) | Updates the form values. Use `replace: true` to fully replace the current values and drop keys that are not present in the new payload. |
| setErrors | (newErrors: object) | Updates the form errors. |
| setTouched | (newTouched: object) | Updates the formβs touched state. |
| reset | ({ values, keepTouched }: IResetOptions<T>) | Resets the form to the initial state or provided values. When new values are provided they become the new initial state and replace missing keys. |
| setFieldValue | (field: string, value: unknown) | Updates the value of a specific field. |
| setFieldTouched | (field: string, touchedValue: boolean) | Marks a specific field as touched. |
| setSubmitting | (value: boolean) | Updates the submitting state. |
| handleSubmit | (e: Event) | Handles form submission, triggers validation, and executes onSubmit. Returns a Promise that resolves after async validation and submission complete. |
| handleFieldBlur | (e: FocusEvent) | Marks the corresponding field as touched on blur. |
| handleFieldChange | (e: Event) | Updates the corresponding fieldβs value and marks it as touched on change. |
| hasFieldError | (field: string): boolean | Checks if a specific field has an error and has been touched. |
| getFieldError | (field: string): string | Retrieves the error message for a specific field if it exists. |
| getFieldValue | (field: string): unknown | Retrieves the current value of a specific field. |
| getFieldTouched | (field: string): boolean|undefined | Checks if a specific field has been touched. |
π Dynamic Fields:
- setFieldValue: Dynamically update specific field values.
- setFieldTouched: Dynamically update the touched state of specific fields.
- β οΈ setFieldError: This method is NOT available. Errors are handled internally through validation rules in the schema.
You can define custom validation rules using the validationSchema parameter. These rules can validate simple fields, arrays, objects, or even arrays of objects.
The above example shows a validation schema for the email and password fields. - **Email** must be valid and is required. - **Password** must be at least 8 characters long and is required.
Validation schemas can be customized to handle simple fields or more complex structures, such as arrays or nested objects.
No worries! Validation rules can be written for arrays, objects, or even arrays of objects.
In the example above, the emails field is an array of email addresses. Each email is validated, and errors are displayed if any email is invalid.
For more complex validation rules, check out the playground section. π
Vue Formik supports both synchronous and asynchronous validation, along with debouncing to optimize performance and user experience.
You can use async validation rules to perform server-side validation, check data availability, or validate complex business logic that requires network requests.
Promise objects (async/await syntax or explicit promises) isValidating flag is automatically set to true during validation When validateOnChange is enabled, validation runs on every field change. For performance optimization and better UX, you can debounce validation to wait for users to finish typing.
validationDebounce sets the delay in milliseconds (default: 0 = no debounce) You can combine async validation with debouncing for optimal performance:
This approach is perfect for scenarios like username availability checks, email validation, or any form with search-like fields that trigger API calls.
For forms with heavy validation logic or API calls, always use debouncing with validateOnChange. The recommended debounce time is between 200-500ms depending on your validation complexity.