无法获取 react-hook-form 以正确验证电子邮件
Cannot get react-hook-form to validate an email properly
我花了很长时间试图让它正确验证,但它没有发生。当关于 email
发生错误时,我在底部添加了一些文本以输出,但无论如何它总是显示 no error
。
编辑:
沙盒 link - https://codesandbox.io/s/damp-star-8gv3l
这是我的输入:
<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>
这是我的钩子:
const {
register,
watch,
control,
formState: { errors, isValid, dirtyFields },
} = useForm<SignupProps>({
defaultValues: {
email: "",
password: "",
confirmPassword: "",
username: "",
firstName: "",
surname: "",
isShop: false,
},
});
根据您的代码和框,这是您需要更改的内容:
- 添加
<form />
标签
- 在
useForm
选项中添加 mode: 'onChange'
以在输入时显示错误
- 如果要在提交时触发验证,请添加提交按钮
- 显示验证通过的错误信息
工作代码和框:https://codesandbox.io/s/autumn-sea-ps37x?file=/pages/index.js
我花了很长时间试图让它正确验证,但它没有发生。当关于 email
发生错误时,我在底部添加了一些文本以输出,但无论如何它总是显示 no error
。
编辑: 沙盒 link - https://codesandbox.io/s/damp-star-8gv3l
这是我的输入:
<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>
这是我的钩子:
const {
register,
watch,
control,
formState: { errors, isValid, dirtyFields },
} = useForm<SignupProps>({
defaultValues: {
email: "",
password: "",
confirmPassword: "",
username: "",
firstName: "",
surname: "",
isShop: false,
},
});
根据您的代码和框,这是您需要更改的内容:
- 添加
<form />
标签 - 在
useForm
选项中添加mode: 'onChange'
以在输入时显示错误 - 如果要在提交时触发验证,请添加提交按钮
- 显示验证通过的错误信息
工作代码和框:https://codesandbox.io/s/autumn-sea-ps37x?file=/pages/index.js