Skip to content

setError

手动设置输入错误

</> setError: (name: string, error: FieldError, { shouldFocus?: boolean }) => void

该功能允许你手动设置一个或多个错误。

¥The function allows you to manually set one or more errors.

属性

¥Props


名称类型描述
namestring输入的名称。
error{ type: string, message?: string, types: MultipleFieldErrors }设置错误及其类型和消息。
config{ shouldFocus?: boolean }设置错误时应集中输入。这仅在注册输入引用时有效,它也不适用于自定义注册。
RULES
  • 如果输入通过了 register 的关联规则,则该方法不会持久化关联的输入错误。

    ¥This method will not persist the associated input error if the input passes register's associated rules.

    register('registerInput', { minLength: 4 });
    setError('registerInput', { type: 'custom', message: 'custom message' });
    // validation will pass as long as minLength requirement pass
  • 与输入字段无关的错误将持续存在,直到使用 clearErrors 清除为止。此行为仅适用于字段级别的内置验证。

    ¥An error that is not associated with an input field will be persisted until cleared with clearErrors. This behaviour is only applicable for built-in validation at field level.

    setError("notRegisteredInput", { type: "custom", message: "custom message" })
    // clearErrors() need to invoked manually to remove that custom error
  • 你可以使用 root 作为键设置服务器或全局错误。这种类型的错误不会在每次提交时持续存在。

    ¥You can set a server or global error with root as the key. This type of error will not persist with each submission.

    setError("root.serverError", {
    type: "400",
    })
    setError("root.random", {
    type: "random",
    })
  • 当你想在异步验证后向用户提供错误反馈时,在 handleSubmit 方法中非常有用。(例如:API 返回验证错误)

    ¥Can be useful in the handleSubmit method when you want to give error feedback to a user after async validation. (ex: API returns validation errors)

  • 当输入被禁用时,shouldFocus 不起作用。

    ¥shouldFocus doesn't work when an input has been disabled.

  • 此方法将强制将 isValid formState 设置为 false。但是,请务必注意,isValid 将始终源自输入注册规则或架构结果的验证结果。

    ¥This method will force set isValid formState to false. However, it's important to be aware that isValid will always be derived from the validation result of your input registration rules or schema result.

  • 需要避免某些关键字,以防止与类型检查发生冲突。他们是 typetypes

    ¥There are certain keywords that need to be avoided to prevent conflicts with type checking. They are type and types.

示例:

¥Examples:


单一错误

¥Single Error

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 { useForm } from "react-hook-form"
const App = () => {
const {
register,
setError,
formState: { errors },
} = useForm()
return (
<form>
<input {...register("test")} />
{errors.test && <p>{errors.test.message}</p>}
<button
type="button"
onClick={() => {
setError("test", { type: "focus" }, { shouldFocus: true })
}}
>
Set Error Focus
</button>
<input type="submit" />
</form>
)
}

多个错误

¥Multiple Errors

import * as React from "react"
import { useForm } from "react-hook-form"
type FormInputs = {
username: string
firstName: 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>}
<button
type="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"
const App = () => {
const {
register,
handleSubmit,
setError,
formState: { errors },
} = useForm()
const onSubmit = (data) => {
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>}
<button
type="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>
)
}

单字段错误

¥Single Field Errors

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",
},
})
}, [setValue])
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 = (data) => {
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>
)
}

服务器错误

¥Server Error

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>
);
};

视频

¥Video


下面的视频详细解释了 setError API。

¥The following video explain setError API in detail.

React Hook Form 中文网 - 粤ICP备13048890号