Reputation: 1116
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,
},
});
Upvotes: 2
Views: 9498
Reputation: 2796
According your codesandbox, here is what you've to change:
<form />
tagmode: 'onChange'
in useForm
options to display the error while typing in the inputWorking codesandbox: https://codesandbox.io/s/autumn-sea-ps37x?file=/pages/index.js
Upvotes: 4