Search code examples
reactjstypescriptmaterial-uireact-hook-formzod

React hook form with Zod and Material ui is not showing any error


This is my ProductInfoForm made with Material UI, and react-hook-form with zod validations, but I have an issue: when I submit the data in the form, it shows the data in the console, but when I want to produce an error, it does not show any error.

//ProductInfoForm Page
'use client';
import React from 'react';
import { Controller, SubmitHandler, useForm } from 'react-hook-form';
import {
  productInfoSchema,
  productInfoSchemaType,
} from '@/utils/validations/AddNewProductFormValidation';
import { Button, TextField } from '@mui/material';
import { zodResolver } from '@hookform/resolvers/zod';

const ProductInfoStep = () => {
  const { handleSubmit, formState, control } = useForm<productInfoSchemaType>({
    mode: 'all',
    reValidateMode: 'onChange',
    resolver: zodResolver(productInfoSchema),
  });

  console.log(formState.errors);

  const onSubmit: SubmitHandler<productInfoSchemaType> = (data) => {
    console.log(data);
  };

  return (
    <div className='p-5 flex flex-col gap-5'>
      <form>
        <Controller
          control={control}
          name='product_name'
          render={({ field }) => (
            <TextField inputRef={field.ref} {...field} label='Product Name' />
          )}
        />
        <div className='justify-end'>
          <Button onClick={handleSubmit(onSubmit)} variant='contained'>
            Next
          </Button>
        </div>
        <div>
          {formState.errors.product_name && <p>Product name is required.</p>}
        </div>
      </form>
    </div>
  );
};

export default ProductInfoStep;
//zod schema
import { z } from 'zod';

export const productInfoSchema = z.object({
  product_name: z.string().min(10).or(z.string().nonempty('required')),
});

export type productInfoSchemaType = z.infer<typeof productInfoSchema>;

I want to get errors, when I submit the form without required validation.


Solution

  • Move handleSubmit(onSubmit) to the onSubmit of the form heres the fixed code

    //ProductInfoForm Page
    'use client';
    import React from 'react';
    import { Controller, SubmitHandler, useForm } from 'react-hook-form';
    import {
      productInfoSchema,
      productInfoSchemaType,
    } from '@/utils/validations/AddNewProductFormValidation';
    import { Button, TextField } from '@mui/material';
    import { zodResolver } from '@hookform/resolvers/zod';
    
    const ProductInfoStep = () => {
      const { handleSubmit, formState, control } = useForm<productInfoSchemaType>({
        mode: 'all',
        reValidateMode: 'onChange',
        resolver: zodResolver(productInfoSchema),
      });
    
      console.log(formState.errors);
    
      const onSubmit: SubmitHandler<productInfoSchemaType> = (data) => {
        console.log(data);
      };
    
      return (
        <div className='p-5 flex flex-col gap-5'>
          <form onSubmit={handleSubmit(onSubmit)}>
            <Controller
              control={control}
              name='product_name'
              render={({ field }) => (
                <TextField inputRef={field.ref} {...field} label='Product Name' />
              )}
            />
            <div className='justify-end'>
              <Button variant='contained' type='submit'>
                Next
              </Button>
            </div>
            <div>
              {formState.errors.product_name && <p>Product name is required.</p>}
            </div>
          </form>
        </div>
      );
    };
    
    export default ProductInfoStep;