</> clearErrors: (name?: string | string[]) => void
该功能可以手动清除表单中的错误。
¥This function can manually clear errors in the form.
属性
¥Props
| 类型 | 描述 | 示例 |
|---|---|---|
| undefined | 删除所有错误。 | clearErrors() |
| string | 删除单个错误。 | clearErrors("yourDetails.firstName") |
| string[] | 删除多个错误。 | clearErrors(["yourDetails.lastName"]) |
-
undefined:重置所有错误¥
undefined: reset all errors -
string:重置单个字段或键名称上的错误。¥
string: reset the error on a single field or by key name.register("test.firstName", { required: true })register("test.lastName", { required: true })clearErrors("test") // will clear both errors from test.firstName and test.lastNameclearErrors("test.firstName") // for clear single input error -
string[]:重置给定字段上的错误¥
string[]: reset errors on the given fields
RULES
-
这不会影响附加到每个输入的验证规则。
¥This will not affect the validation rules attached to each inputs.
-
此方法不会影响验证规则或
isValidformState。¥This method doesn't affect validation rules or
isValidformState.
示例
¥Examples
import * as React from "react"import { useForm } from "react-hook-form"type FormInputs = {firstName: stringlastName: stringusername: string}const App = () => {const {register,formState: { errors },handleSubmit,clearErrors,} = useForm<FormInputs>()const onSubmit = (data: FormInputs) => {console.log(data)}return (<form onSubmit={handleSubmit(onSubmit)}><input {...register("firstName", { required: true })} /><input {...register("lastName", { required: true })} /><input {...register("username", { required: true })} /><button type="button" onClick={() => clearErrors("firstName")}>Clear First Name Errors</button><buttontype="button"onClick={() => clearErrors(["firstName", "lastName"])}>Clear First and Last Name Errors</button><button type="button" onClick={() => clearErrors()}>Clear All Errors</button><input type="submit" /></form>)}