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 | object: <T> | true | - | An object containing the initial values for the form fields. |
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. |
validationSchema | FormikValidationSchema<T> | false | - | A custom validation rules object for validating the form fields. |
onSubmit | FormikOnSubmit<T> | false | - | A function to handle form submission. It receives the current form values and helpers. |
validateOnMount | boolean | false | true | If true, performs validation when the form is initialized. |
preventDefault | boolean | false | true | If true, prevents the default form submission behavior. |
π Notes:
The validation schema can be supplied as
yupSchema
,joiSchema
,zodSchema
orvalidationSchema
parameters.If any of the schema parameters are not provided, the form will not perform any validation.
Please use Object schemas for
Yup
andJoi
and not thestring
schemas.
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.setSubmitting
- Sets the submitting state of the form.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. |
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
&isDirty
are computed properties. Don't forget to use.value
while accessing it inside the template.
Method | Parameters | Description |
---|---|---|
setValues | (newValues: Partial<T>) | Updates the form values. |
setErrors | (newErrors: object) | Updates the form errors. |
setTouched | (newTouched: object) | Updates the formβs touched state. |
reset | ({ values }: { values?: Partial<T> }) | Resets the form to the initial state or provided values. |
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. |
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.
const initialValues = {
email: "",
password: "",
confirmPassword: "",
}
const validationSchema = {
email: (value: string) => {
if (!value) {
return "Email is required";
}
if (!isEmail(value)) {
return "Invalid email";
}
},
password: (value: string) => {
if (!value) {
return "Password is required";
}
if (value.length < 8) {
return "Password must be at least 8 characters";
}
},
confirmPassword: (value: string) => {
if (!value) {
return "Confirm password is required";
}
if (value !== initialValues.password) {
return "Passwords do not match";
}
},
}
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.
const initialValues = {
email: [""],
}
const validationSchema = {
email: (values: string[]) => {
if (!values?.length) {
return "Email is required";
}
const errs = [];
values.forEach((value, index) => {
if (!value) {
errs.push("Email is required");
return; // Skip further validation
}
if (!isEmail(value)) {
errs.push("Invalid email");
}
});
}
}
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. π