aboutsummaryrefslogtreecommitdiff
path: root/src/signUpSchema.ts
blob: 338e137c5a094bed1f8aa1108f72f23750df109e (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
52
53
54
55
56
57
58
59
60
61
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}`)