Skip to content

setError

입력 에러를 수동으로 설정하기

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

이 함수는 하나 이상의 에러를 수동으로 설정할 수 있도록 합니다.

Props


NameTypeDescription
namestring입력 필드의 이름.
error{ type: string, message?: string, types: MultipleFieldErrors }에러 타입과 메시지를 설정합니다.
config{ shouldFocus?: boolean }에러 설정 시 입력 필드에 포커스를 줄지 여부를 설정합니다. 이 기능은 입력 필드의 참조가 등록되어 있을 때만 동작하며, custom register에는 작동하지 않습니다.
RULES
  • 이 메서드는 입력이 register의 연관된 규칙을 통과한 경우, 관련 입력 에러를 유지하지 않습니다.
    register("registerInput", { minLength: 4 })
    setError("registerInput", { type: "custom", message: "custom message" })
    // minLength 요구 사항을 충족하는 한 유효성 검사는 통과합니다.
  • 입력 필드와 연관되지 않은 에러는 clearErrors를 통해 지워질 때까지 지속됩니다. 이 동작은 필드 수준에서의 내장 유효성 검사에만 해당됩니다.
    setError("notRegisteredInput", { type: "custom", message: "custom message" })
    // 해당 에러를 제거하려면 clearErrors()를 수동으로 호출해야 합니다.
  • root를 키로 서버 또는 전역 에러를 설정할 수 있습니다. 이러한 유형의 에러는 각 submission마다 유지되지 않습니다.
    setError("root.serverError", {
    type: "400",
    })
    setError("root.random", {
    type: "random",
    })
  • 이 메서드는 비동기 유효성 검사 후, 사용자에게 에러 피드백을 제공하려는 경우, handleSubmit 메서드에서 유용할 수 있습니다. (예: API에서 유효성 검사 에러 반환 시)
  • shouldFocus는 입력 필드가 비활성화된 경우 작동하지 않습니다.
  • 이 메서드는 isValid 폼 상태를 false로 강제 설정합니다. 그러나 isValid는 항상 입력 등록 규칙 또는 스키마 결과의 유효성 검사 결과에서 파생된다는 점에 유의해야 합니다.
  • 타입 검사를 방해하지 않기 위해 typetypes라는 키워드는 피해야 합니다.

Examples:


단일 에러 설정

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

다중 에러 설정

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: "한 번 더 확인하세요.",
},
{
type: "manual",
name: "firstName",
message: "세 번 더 확인하세요.",
},
]
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: "한 번 더 확인하세요.",
},
{
type: "manual",
name: "firstName",
message: "세 번 더 확인하세요.",
},
]
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: "이 필드는 필수입니다.",
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: "이 필드는 필수입니다.",
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>
);
};

Video


다음 비디오는 setError API에 대해 자세히 설명합니다.

지원해 주셔서 감사합니다

프로젝트에서 React Hook Form이 유용하다고 생각하신다면, 스타를 눌러 지원해 주시길 부탁드립니다.