본문으로 건너뛰기

setError

</> setError: UseFormSetError

이 함수를 사용하면 필드에 오류를 수동으로 설정할 수 있습니다. 여러 번 호출하여 여러 필드에 오류를 설정할 수 있습니다.

Props


이름타입설명
namestring입력 이름입니다.
error{ type?: string, message?: string, types?: MultipleFieldErrors }type (선택 사항) — 오류 출처의 식별자입니다(예: "required", "custom", "serverError"). errors[name].type으로 노출됩니다.

message (선택 사항) — 사람이 읽을 수 있는 오류 메시지입니다. errors[name].message로 노출됩니다.

types (선택 사항) — 오류 타입을 키로 사용하여 단일 필드에 여러 메시지를 할당하는 Record<string, string | boolean>입니다(예: { required: "This is required", minLength: "Too short" }). errors[name].types로 노출됩니다. 동일한 필드의 검증 메시지를 동시에 두 개 이상 표시해야 할 때 message 대신 사용합니다. 내장 또는 스키마 검증도 같은 방식으로 채우려면 폼에 criteriaMode: "all"을 설정하여 types를 사용합니다.
options{ shouldFocus?: boolean }오류를 설정할 때 입력에 포커스할지 여부입니다. 입력의 참조가 등록된 경우에만 동작하며 사용자 정의 register에서는 동작하지 않습니다.
예제:

단일 오류

import { useEffect } 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)
}

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

여러 오류

setError는 호출할 때마다 정확히 하나의 오류를 설정합니다. 여러 필드에 오류를 설정하려면 필드마다 한 번씩 호출합니다. 일반적으로 서버의 오류 응답을 순회하는 루프에서 호출합니다.

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

단일 필드의 여러 오류

typescriteriaMode: "all"과 함께 사용하여 단일 필드에 여러 검증 메시지를 동시에 연결합니다. 객체의 각 키는 오류 타입 식별자이며, 각 값은 해당 규칙에 표시할 메시지입니다.

import { useEffect } 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)

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 { 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를 자세히 설명합니다.