如何让react-hook-form仅在提交时验证,避免失败后实时校验?
解决react-hook-form仅在提交时验证、禁止实时重验证的方案
核心配置要点
要实现「仅在提交时触发验证,提交失败后输入/粘贴操作不实时重验证」,只需修改useForm的两个关键配置:
mode: 'onSubmit':限定仅在表单提交时触发所有验证规则reValidateMode: 'onSubmit':表单值变化后,仅在再次提交时重新执行验证(默认onChange会实时触发重验证)
代码示例
基础表单验证(必填+格式校验)
import { useForm } from "react-hook-form"; type FormInputs = { email: string; }; export default function App() { const { register, handleSubmit, formState: { errors }, } = useForm<FormInputs>({ mode: "onSubmit", reValidateMode: "onSubmit", }); const onSubmit = (data: FormInputs) => { console.log("提交数据:", data); // 此处添加后端提交逻辑 }; return ( <form onSubmit={handleSubmit(onSubmit)}> <input {...register("email", { required: "邮箱不能为空", pattern: { value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: "邮箱格式不正确", }, })} placeholder="请输入邮箱" /> {errors.email && <p style={{ color: "red" }}>{errors.email.message}</p>} <button type="submit">提交</button> </form> ); }
包含后端验证的场景
如果需要在提交时调用后端接口做校验(比如检查邮箱是否已注册),可通过异步自定义验证规则实现,配合上述配置确保仅在提交时发起后端请求:
import { useForm } from "react-hook-form"; type FormInputs = { email: string; }; // 模拟后端验证接口 const checkEmailExists = async (email: string): Promise<boolean> => { await new Promise(resolve => setTimeout(resolve, 1000)); return email === "exists@example.com"; }; export default function App() { const { register, handleSubmit, formState: { errors, isSubmitting }, } = useForm<FormInputs>({ mode: "onSubmit", reValidateMode: "onSubmit", }); const onSubmit = (data: FormInputs) => { console.log("提交数据:", data); // 后端提交逻辑 }; return ( <form onSubmit={handleSubmit(onSubmit)}> <input {...register("email", { required: "邮箱不能为空", pattern: { value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: "邮箱格式不正确", }, validate: async (value) => { const exists = await checkEmailExists(value); return exists ? "该邮箱已被注册" : true; }, })} placeholder="请输入邮箱" disabled={isSubmitting} /> {errors.email && <p style={{ color: "red" }}>{errors.email.message}</p>} <button type="submit" disabled={isSubmitting}> {isSubmitting ? "验证中..." : "提交"} </button> </form> ); }
效果说明
- 首次提交空输入框,会触发必填项错误提示;此时输入/粘贴不符合格式的内容,不会实时触发验证,错误提示会保留至再次提交
- 再次提交时,会重新校验所有规则(包括后端验证),仅验证通过后才会执行提交逻辑
- 后端验证请求仅在提交时发起,不会因输入/粘贴操作频繁调用接口
内容的提问来源于stack exchange,提问作者user3486427
相关产品推荐
相关产品推荐

