</> setError:
(name: string, error: FieldError, { shouldFocus?: boolean }) => void
この関数は、1つ以上のエラーを手動で設定できます。
プロパティ
名前 | 型 | 説明 |
---|---|---|
name | 文字列 | 入力の名前。 |
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がプロジェクトで役立つと思われる場合は、スターをつけてサポートをご検討ください。