Creating a Custom Function for React Hook Form: Validate Without Submitting

Samir Mirzaliyev
2 min readSep 29, 2024

--

When working with forms in React, using a tool like React Hook Form allows you to efficiently manage the form state. However, there are cases where you may want to validate the form and retrieve its values without actually submitting it. This is especially useful for displaying real-time validation errors or dynamically updating values.

In this article, we’ll explore how to build a utility function that validates form values and retrieves any errors using Zod for schema validation. This function can be integrated into your React Hook Form workflow, allowing you to check values without submission.

We define two types: SuccessValidation and FailedValidation. These types help structure the result of the form validation, whether it passes or fails.

export type SuccessValidation<T extends z.ZodRawShape> = {
isFormValid: boolean;
values: {
[k in keyof z.baseObjectOutputType<T>]: z.baseObjectOutputType<T>[k];
};
};

export type FailedValidation<T extends z.ZodRawShape> = {
isFormValid: boolean;
errors: { name: keyof z.baseObjectOutputType<T>; error: string }[];
};
  • isFormValid: boolean
  • errors: An array of validation errors. Each error includes the field name (name) and the error message (error).
  export function handleSubmitForm<T extends z.ZodRawShape>(
scheme: z.ZodObject<T>,
values: z.infer<z.ZodObject<T>>
): SuccessValidation<T> | FailedValidation<T> {

const result = scheme.safeParse(values);

// Return valid values if validation passes
if (result.success) {
return { isFormValid: true, values: result.data };
}

// If validation fails, gather the errors
const errors = result.error.issues.reduce(
(acc, issue) => {
const key = issue.path[0] as keyof z.baseObjectOutputType<T>;
const message = issue.message;
acc.push({
name: key,
error: message,
});
return acc;
},
[] as { name: keyof z.baseObjectOutputType<T>; error: string }[]
);

// Return the errors and mark form as invalid
return {
isFormValid: false,
errors,
};
}

The core of the function is Zod’s safeParse method, which validates the values object against the provided schema. The safeParse method returns an object with the following:

  • If validation succeeds, it returns success: true and validated data.
  • If validation fails, it returns success: false and error details.

If validation fails, we extract the error details using the result.error.issues array. Each issue contains details such as the field path and error message.

Creating this custom function allows you to implement comprehensive form validation in your React applications using React Hook Form and Zod. This method enables you to validate and retrieve form values at any point without needing to submit the form, thereby improving both developer and user experience

--

--

Samir Mirzaliyev
Samir Mirzaliyev

No responses yet