aboutsummaryrefslogtreecommitdiff
path: root/src/signUpSchema.ts
blob: 4d8b71f0886ee5ce38813aef5831540f515ba1b6 (about) (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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 addRefine = <Form1 extends z.ZodTypeAny>(schema: Form1) => (
  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 type Form1 = z.infer<typeof form1SchemaWithoutRefine>

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文字以下で入力してください' })
})

export type Form2 = z.infer<typeof form2Schema>

const formSchemaWithoutRefine = form1SchemaWithoutRefine.merge(form2Schema)

export type Form = z.infer<typeof formSchemaWithoutRefine>

export const form1Schema = addRefine(form1SchemaWithoutRefine)
export const formSchema = addRefine(formSchemaWithoutRefine)