最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Cannot get react-hook-form to validate an email properly - Stack Overflow

programmeradmin2浏览0评论

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 -

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,
    },
  });

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,
    },
  });
Share Improve this question edited Dec 17, 2021 at 15:46 squish asked Dec 17, 2021 at 15:29 squishsquish 1,1262 gold badges17 silver badges33 bronze badges 5
  • Can you provide a codesandbox please ? It's easier to help you – Joris Commented Dec 17, 2021 at 15:34
  • Sure thing! one moment @Joris – squish Commented Dec 17, 2021 at 15:38
  • @Joris link added! thank you – squish Commented Dec 17, 2021 at 15:46
  • The main issue I see here is that there is no form, and no way to submit the form. – Jake Worth Commented Dec 17, 2021 at 15:53
  • @JakeWorth in my actual file I have a form and a way to submit, Im just struggling with the inputs and their validations. – squish Commented Dec 17, 2021 at 15:56
Add a ment  | 

1 Answer 1

Reset to default 4

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

发布评论

评论列表(0)

  1. 暂无评论