How to log form validation using zod and react-hook-form like in this svelte tutorial?
P粉421119778
P粉421119778 2024-01-28 23:16:11
0
1
480

I tried to follow the zod verification tutorial in svelte. I have no experience with this (svelte) so I'm wondering how can I replicate this code functionality in a simple React/next app? I'm stuck on what ({request}) will be/will be passed to the async function.

Also, should this be done inside useEffect or only called on 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 repository for this tutorial: https://github.com/huntabyte/sveltekit-form-validation/blob/main/src/routes/+page.server.js

P粉421119778
P粉421119778

reply all(1)
P粉714780768

This is what I did:

  1. First, I defined the validation schema using zod.
  2. I then created a custom hook to handle form submission and validation. In this hook, I used the useForm hook from react-hook-form to manage the form state.
  3. To handle form submission, I pass the handleSubmit function from useForm to my custom hook.
  4. In the handleSubmit function, I used the parse method in the zod validation architecture to validate the form data.
  5. If the validation is successful, I will log the form data to the console. If not, I return an object containing the form data and any validation errors.

Overall, I find this approach works well and is easy to understand and implement. As for your question about where to put the validation code, I would suggest calling it on form submission rather than calling it in useEffect.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template