For email inputs, how to avoid the warning "Please include an @ ..." to show up right away?
#13267
Replies: 2 comments 1 reply
-
|
You can't currently change the validation mode on a per-field basis in react-hook-form (see #13085, which has a status of "Pending Feature Requests"). This has been implemented in RHF Plus, which is intended to be a compatible replacement for react-hook-form with some additional opt-in features. See the docs. Disclaimer: I haven't used RHF-plus and I can't confirm how well that feature works. |
Beta Was this translation helpful? Give feedback.
-
|
The issue is that Workaround without per-field mode: You can disable native validation for just the email field by using <input
autoFocus={true}
autoComplete="email"
placeholder={emailInputPlaceholder}
spellCheck={false}
type="text" // Use "text" instead of "email"
inputMode="email" // Still shows email keyboard on mobile
{...register("email", {
required: "Email is required",
validate: (value) =>
/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value) || "Please enter a valid email address",
})}
/>This gives you:
The key insight is that native validation warnings come from the |
Beta Was this translation helpful? Give feedback.
-
|
When If the validation React Hook Form does not support overriding the validation 1. Disable Native Validation and use Custom UI Messages (Recommended)Native tooltips are difficult to style, cannot be customized easily, and have inconsistent behaviors across browsers. The standard practice is to disable native validation and display custom, accessible error messages: const { register, formState: { errors } } = useForm({
mode: "onChange" // Keep change validation
});
return (
<div>
<input
type="email"
{...register("email", {
required: "Email is required",
pattern: {
value: /\S+@\S+\.\S+/,
message: "Please include an '@' in the email address"
}
})}
/>
{errors.email && <span role="alert" className="error">{errors.email.message}</span>}
</div>
);2. Set Validation Mode to
|
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
For this email address input, I only typed
mand that warning already comes up right away which is quite annoying.I'm using react-hook-form while
shouldUseNativeValidationis set to true and the mode is set toonChange.And the React-based markup is
It's all legit. When you go to Mozilla, this doesn't happen there:
https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/input/email
I understand, it's about the mode. Default is
onSubmit. Then this doesn't happen.But for some other form inputs, like changing and confirming passwords, I'd like to stick to
onChange.Would it be possible to define this mode by input base instead of form?
Beta Was this translation helpful? Give feedback.
All reactions