import * as z from "zod" import parsePhoneNumber from 'libphonenumber-js' const kanaRegex = /^[ァ-ン]+$/; const form1SchemaWithoutRefine = z.object({ name: z.string().min(1, { message: '必須項目です' }), kana: z.string().min(1, { message: '必須項目です' }).regex(kanaRegex, { message: 'カタカナを入力してください' }), tel1: z.string(), tel2: z.string(), tel3: z.string(), }) const addTelRefine = <Form1Data extends z.ZodTypeAny>(schema: Form1Data) => ( schema.refine( ({ tel1, tel2, tel3 }) => (tel1.length > 0 && tel2.length > 0 && tel3.length > 0), { message: '必須項目です', path: ['tel3'], } ).refine( ({ tel1, tel2, tel3 }) => { const phoneNumber = parsePhoneNumber('+81' + `${tel1}${tel2}${tel3}`) console.log([`${tel1}${tel2}${tel3}`, phoneNumber?.isValid()]) return phoneNumber?.isValid() }, { message: '電話番号が不正です', path: ['tel3'], } )) export const form2Schema = z.object({ email: z.string().min(1, { message: '必須項目です' }).email({ message: 'メールアドレスを入力してください' }), password: z.string() .min(1, { message: '必須項目です' }) .min(12, { message: '12文字以上で入力してください' }) .max(128, { message: '128文字以下で入力してください' }) }) // const favLangSchema = z.object({ // name: z.string() // }) export const form3Schema = z.object({ // favLangs: z.array(favLangSchema), hasGithubRepo: z.boolean(), githubUsername: z.string(), repoName: z.string(), }) const formSchemaWithoutRefine = form1SchemaWithoutRefine.merge(form2Schema).merge(form3Schema) export const form1Schema = addTelRefine(form1SchemaWithoutRefine) export const formSchema = addTelRefine(formSchemaWithoutRefine) export type Form1Data = z.infer<typeof form1SchemaWithoutRefine> export type Form2Data = z.infer<typeof form2Schema> export type Form3Data = z.infer<typeof form3Schema> export type FormData = z.infer<typeof formSchemaWithoutRefine> export const displayTel = ({ tel1, tel2, tel3 }: Form1Data) => (`${tel1}-${tel2}-${tel3}`)