Home > OS >  Cannot get react-hook-form to validate an email properly
Cannot get react-hook-form to validate an email properly

Time:12-18

I have spent ages trying to get this to validate properly but it just isn't happening. Ive added some text at the bottom to output when an error occurs regarding the email however it always says no error, no matter what.

Edit: Sandbox link - https://codesandbox.io/s/damp-star-8gv3l

Here is my input:

           <div>
              <label
                htmlFor="email"
                className="block text-sm font-medium text-gray-700"
              >
                Email address
              </label>
              <div className="mt-1">
                <input
                  {...register("email", {
                    required: {
                      value: true,
                      message: "Please enter your email address",
                    },
                    pattern: {
                      value:
                        /^(([^<>()[\]\\.,;:\s@\"] (\.[^<>()[\]\\.,;:\s@\"] )*)|(\". \"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9] \.) [a-zA-Z]{2,}))$/,
                      message: "Invalid email address",
                    },
                  })}
                  id="email"
                  name="email"
                  type="email"
                  autoComplete="off"
                  className={`input w-full ${
                    !errors.email && dirtyFields.email && "!bg-green-50"
                  }`}
                />
              </div>
              {errors.email ? "error" : "no error"}
              {errors.email?.message && (
                <ErrorMessage>{errors.email?.message}</ErrorMessage>
              )}
            </div>

Here is my hook:

  const {
    register,
    watch,
    control,
    formState: { errors, isValid, dirtyFields },
  } = useForm<SignupProps>({
    defaultValues: {
      email: "",
      password: "",
      confirmPassword: "",
      username: "",
      firstName: "",
      surname: "",
      isShop: false,
    },
  });

CodePudding user response:

According your codesandbox, here is what you've to change:

  • Add <form /> tag
  • Add mode: 'onChange' in useForm options to display the error while typing in the input
  • Add a submit button if you want to trigger validation on submit
  • Display error message passed in validation

Working codesandbox: https://codesandbox.io/s/autumn-sea-ps37x?file=/pages/index.js

  • Related