Search code examples
reactjsformsreact-hookssveltezod

How do I log form validation with zod and react-hook-form like in this svelte tutorial?


I tried to follow along with a zod validation tutorial that is in svelte. I have no experience with this (svelte) so I'm wonder how do I replicate this codes functionality inside of a simple react/next app? I'm stuck on what ({request}) would be/what I'd be passing to the async function.

Additionally, should this be going inside of a useEffect or just called upon form submission?

export const actions = {
default: async ({ request }) => {
    const formData = Object.fromEntries(await request.formData());
    console.log('Form Data:', formData);

    try {
        const result = registerSchema.parse(formData);
        console.log('SUCCESS');
        console.log(result);
    } catch (err) {
        const { fieldErrors: errors } = err.flatten();
        const { password, passwordConfirm, ...rest } = formData;
        return {
            data: rest,
            errors
        };
    }
};

here is the repo for the tutorial: https://github.com/huntabyte/sveltekit-form-validation/blob/main/src/routes/%2Bpage.server.js


Solution

  • Here's what I did:

    1. First, I defined my validation schema using zod.
    2. Then, I created a custom hook that handles the form submission and validation. Inside this hook, I used the useForm hook from react-hook-form to manage the form state.
    3. To handle form submission, I passed the handleSubmit function from useForm to my custom hook.
    4. Inside the handleSubmit function, I used the parse method from my zod validation schema to validate the form data.
    5. If validation was successful, I logged the form data to the console. If not, I returned an object with the form data and any validation errors.

    Overall, I found that this approach worked well and was easy to understand and implement. As for your question about where to put the validation code, I would recommend calling it on form submission rather than inside useEffect.