跳到内容

clearErrors

清除表单错误

</> clearErrors: (name?: string | string[]) => void

此函数可以手动清除表单中的错误。

参数


类型描述示例
undefined删除所有错误。clearErrors()
string删除单个错误。clearErrors("yourDetails.firstName")
string[]删除多个错误。clearErrors(["yourDetails.lastName"])
  • undefined: 重置所有错误

  • string: 重置单个字段或键名的错误。

    register("test.firstName", { required: true })
    register("test.lastName", { required: true })
    clearErrors("test") // will clear both errors from test.firstName and test.lastName
    clearErrors("test.firstName") // for clear single input error
  • string[]: 重置给定字段的错误

规则
  • 这不会影响附加到每个输入的验证规则。
  • 此方法不会影响验证规则或isValid formState。

示例


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

感谢您的支持

如果您发现 React Hook Form 在您的项目中很有用,请考虑为它点赞和支持它。