"use server"
import {z} from 'zod'
const formSchema = z.object({
username:z.string().min(5).max(10),
email:z.string().email(),
password:z.string().min(10),
passwordConfirm:z.string().min(10)
})
export async function createAccount(prev:any,data:FormData) {
const formData = {
username:data.get("username"),
email:data.get('email'),
password:data.get('password'),
passwordConfirm:data.get('passwordConfirm')
}
formSchema.parse(formData)
}
formSchema.parse(formData)
//데이터를 검증
//safeParse을 통해 formSchema의 형식에 맞는지 formData를 데이터 검증한다
const result = formSchema.safeParse(formData)
flatten을 사용한다.//action.ts
if(!result.success){
console.log(result.error.flatten())
return result.error.flatten()
}
//page.tsx
const [state ,action] = useActionState(createAccount,null)
<FormInput name="username" type="text" placeholder="Username" required errors={state?.fieldErrors.username}/>
//username에서 특정 문구를 포함하고 있는지 확인
const formSchema = z.object({
username:z.string({
invalid_type_error:"user name must be a string",
required_error:"Where is my username?"
}).min(5,"Way too short").max(10,"That is too long")
.refine(username => !username.includes('hi'),"No hi allowed")
})
//form전체에 검증을 했기에 오류메시지는 formError메세지로 나타난다.
const formSchema = z.object({
}).refine(({password,passwordConfirm}) => password === passwordConfirm,"Both passwords should be the same")
//error문구를 confimPassword에 주기위해 아래 코드로 변경
.refine(({password,passwordConfirm}) => password === passwordConfirm,{
message:"Both passwords should be the same",
path:["passwordConfirm"]
})
const passwordRegex = new RegExp(
/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*?[#?!@$%^&*-]).+$/
);
const formSchema = z.object({
password:z.string().min(10).regex(passwordRegex,"password must have lowercase...etc"),
})
username:z.string().trim()
zod를 사용해 form 유효성 검사를 하는건 정말 신세계라는걸 배웠다. 엄청난 정규식을 만들지 않아도 zod에 모든 기능들이 다 있기에 쉽게 유효성 검사를 할 수 있을거 같다.