Typescript를 위한 스키마 선언 및 유효성 검증 라이브러리, react-hook-form에서 호환성이 좋음
만약 기획자의 요구사항이 다음과 같다면
id : 문자열, 3자 이상,
password: 문자열, 최대7자
복잡하게 state와 if-else문으로 검사하는것 대신 zod를 이용해 아래와 같이 유효성 검증을 할 수 있다.
import {z} from 'zod'
const schema = z.object({ // 스키마 생성
id: z.string().min(3,'아이디는 3자 이상이어야 합니다'), // 메서드 체이닝방식 사용
password: z.string({
invalid_type_error: '패스워드는 문자열이어야 합니다' // 타입에 대한 에러(option)
}).max(7, '패스워드는 7자를 넘을 수 없습니다.') // 길이에 대한 에러(option)
})
// const result = schema.parse({
// id: '',
// password: 22323
// })
const success = schema.safeParse({
id: 'ryan',
password: '1234'
})
const failedResult = schema.safeParse({
id: '',
password: 22323
})
// 검증 실패
console.log(failedResult) // { success: false, error: [Getter] }
console.log(failedResult?.error) // ZodError객체 출력
console.log(failedResult.error?.message) // [
{
"code": "invalid_type",
"expected": "string",
"received": "number",
"path": [
"패스워드"
],
"message": "패스워드는 문자열이어야 합니다"
}
]
// 검증 성공
console.log(success) // { success: true, data: { 'id': 'ryan', 'password': '1234' }}
// 타입 추론
type SchemaType = z.infer<typeof schema> // 타입 지정 자동 (폼)
위 코드에서 schema.parse() 와 schema.safeParse() 메서드의 차이는 다음과 같다.
form을 다루는 유명한 라이브러리로 react-hook-form이 존재한다.
보통 react-hook-form에서 유효성 검사기능은 zod와 같은 서드파티 라이브러리와 같이 사용하는데(zod의 이점이 훨씬 크기때문), hook-form과 zod를 연결해주는 메서드를 hookform에서 따로 지원한다.
import { zodResolver } from "@hookform/resolvers/zod"; // 훅폼과 zod 연결
const schema = z.object({...})
type FormType = z.infer<typeof schema>;
const methods = useForm<FormType>({ // core of hook-form
resolver: zodResolver(schema) // resolving
...
})
또한 zod의 schema와 그 바탕으로 추론된 FormType을 react-hook-form에서 타입으로 적용하기 매우 좋음