</> setError:
(name: string, error: FieldError, { shouldFocus?: boolean }) => void
该函数允许您手动设置一个或多个错误。
参数
名称 | 类型 | 描述 |
---|---|---|
name | string | 输入的名称。 |
error | { type: string, message?: string, types: MultipleFieldErrors } | 设置错误及其类型和消息。 |
config | { shouldFocus?: boolean } | 在设置错误时是否应将焦点放在输入上。这仅在输入的引用已注册时才有效,它对自定义注册无效。 |
规则
- 如果输入通过
register
的关联规则,则此方法不会保留关联的输入错误。register('registerInput', { minLength: 4 });setError('registerInput', { type: 'custom', message: 'custom message' });// validation will pass as long as minLength requirement pass - 与输入字段无关的错误将保留,直到使用
clearErrors
清除。 此行为仅适用于字段级别的内置验证。setError("notRegisteredInput", { type: "custom", message: "custom message" })// clearErrors() need to invoked manually to remove that custom error - 您可以使用
root
作为键来设置服务器或全局错误。 这种类型的错误不会随着每次提交而保留。setError("root.serverError", {type: "400",})setError("root.random", {type: "random",}) - 在您想要在异步验证后向用户提供错误反馈时(例如:API 返回验证错误),这在
handleSubmit
方法中很有用。 shouldFocus
在输入被禁用时不起作用。- 此方法将强制将
isValid
formState 设置为false
。 但是,请注意,isValid
将始终从您的输入注册规则或模式结果的验证结果中得出。 - 有一些关键字需要避免,以防止与类型检查冲突。 它们是
type
和types
。
示例
单个错误
import * as React from "react"import { useForm } from "react-hook-form"type FormInputs = {username: string}const App = () => {const {register,handleSubmit,setError,formState: { errors },} = useForm<FormInputs>()const onSubmit = (data: FormInputs) => {console.log(data)}React.useEffect(() => {setError("username", {type: "manual",message: "Dont Forget Your Username Should Be Cool!",})}, [setError])return (<form onSubmit={handleSubmit(onSubmit)}><input {...register("username")} />{errors.username && <p>{errors.username.message}</p>}<input type="submit" /></form>)}
多个错误
import * as React from "react"import { useForm } from "react-hook-form"type FormInputs = {username: stringfirstName: string}const App = () => {const {register,handleSubmit,setError,formState: { errors },} = useForm<FormInputs>()const onSubmit = (data: FormInputs) => {console.log(data)}return (<form onSubmit={handleSubmit(onSubmit)}><label>Username</label><input {...register("username")} />{errors.username && <p>{errors.username.message}</p>}<label>First Name</label><input {...register("firstName")} />{errors.firstName && <p>{errors.firstName.message}</p>}<buttontype="button"onClick={() => {const inputs = [{type: "manual",name: "username",message: "Double Check This",},{type: "manual",name: "firstName",message: "Triple Check This",},]inputs.forEach(({ name, type, message }) => {setError(name, { type, message })})}}>Trigger Name Errors</button><input type="submit" /></form>)}
单个字段错误
import * as React from "react"import { useForm } from "react-hook-form"type FormInputs = {lastName: string}const App = () => {const {register,handleSubmit,setError,formState: { errors },} = useForm<FormInputs>({criteriaMode: "all",})const onSubmit = (data: FormInputs) => console.log(data)React.useEffect(() => {setError("lastName", {types: {required: "This is required",minLength: "This is minLength",},})}, [setError])return (<form onSubmit={handleSubmit(onSubmit)}><label>Last Name</label><input {...register("lastName")} />{errors.lastName && errors.lastName.types && (<p>{errors.lastName.types.required}</p>)}{errors.lastName && errors.lastName.types && (<p>{errors.lastName.types.minLength}</p>)}<input type="submit" /></form>)}
服务器错误
import * as React from "react";import { useForm } from "react-hook-form";const App = () => {const { register, handleSubmit, setError, formState: { errors } } = useForm({criteriaMode: 'all',});const onSubmit = async () => {const response = await fetch(...)if (response.statusCode > 200) {setError('root.serverError', {type: response.statusCode,})}}return (<form onSubmit={handleSubmit(onSubmit)}><label>Last Name</label><input {...register("lastName")} />{errors.root.serverError.type === 400 && <p>server response message</p>}<button>submit</button></form>);};
视频
以下视频详细解释了setError
API。
感谢您的支持
如果您发现 React Hook Form 在您的项目中很有用,请考虑给它加星号并支持它。