Search code examples
javascriptreactjstypescriptreact-hook-formzod

How to remove default html mail error message and make zod message instead with react-hook-form


this is my schema. using react-hook-form & zod for validation

const emailInputSchema = z.object({
  email: z.string().min(1, "input is required").email("email address is not valid"),
});

I want to have the message email address is not valid instead of the standard HTML email error message:

enter image description here

I want to have the input is required but I don't get this error in the error object.

  const {
    register,
    handleSubmit,
    formState: { errors, isSubmitting },
    reset,
  } = useForm<TEmailInputSchema>({
    resolver: zodResolver(emailInputSchema, { errorMap: customErrorMap }),
  });

and here is the form inside of the TSX:

      <form onSubmit={handleSubmit(handleMailSubmit)}>
        <div className="input-container">
          <div className="input-wrapper rounded">
            <FaRegEnvelope className="input-icon" />
            <input
              type="email"
              {...register("email")}
              placeholder="email"
              className="input"
              autoComplete="email"
            />
          </div>
        </div>
        {errors.email && (
          <p className={`${errorStyle}`}>{`${errors.email.message}`}</p>
        )}
        <div className="buttons-container">
          <button
            type="submit"
            disabled={isSubmitting}
            className="form-submit-button"
          >
            Send an email
          </button>
        </div>
      </form>

Solution

  • You need to use noValidate prop on form element. Something like:

    <form onSubmit={handleSubmit(handleMailSubmit)} noValidate>
            <div className="input-container">
              <div className="input-wrapper rounded">
                <FaRegEnvelope className="input-icon" />
                <input
                  type="email"
                  {...register("email")}
                  placeholder="email"
                  className="input"
                  autoComplete="email"
                />
              </div>
            </div>
            {errors.email && (
              <p className={`${errorStyle}`}>{`${errors.email.message}`}</p>
            )}
            <div className="buttons-container">
              <button
                type="submit"
                disabled={isSubmitting}
                className="form-submit-button"
              >
                Send an email
              </button>
            </div>
          </form>