aboutsummaryrefslogtreecommitdiff
path: root/src/SignUpForm1.tsx
blob: fee515f516c96d6ca307db0d2c4f0f4cf463e18d (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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import './SignUp.css'
import { useForm } from 'react-hook-form'
import { zodResolver } from "@hookform/resolvers/zod"
import * as z from "zod"
import parsePhoneNumber from 'libphonenumber-js'

const kanaRegex = /^[ァ-ン]+$/

const schema = 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(),
}).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'],
  }
)

type Form1 = {
  name: string,
  kana: string,
  tel1: string,
  tel2: string,
  tel3: string,
}

export const SignUpForm1 = () => {
  const { register, handleSubmit, formState: { errors } } = useForm<Form1>({
    resolver: zodResolver(schema),
  });

  const onsubmit = (data: Form1) => console.log(data);
  const onerror = (err: any) => console.log(err);

  return (
    <>
      <h1>会員登録 フェーズ 1</h1>
      <form className="SignUpForm" onSubmit={handleSubmit(onsubmit, onerror)}>
        <div>
          <label htmlFor="name">名前: </label>
          <input id="name" type="text" {...register('name')}></input>
          <div className="error">{errors.name?.message}</div>
        </div>
        <div>
          <label htmlFor="kana">名前カナ: </label>
          <input id="kana" type="text" {...register('kana')}></input>
          <div className="error">{errors.kana?.message}</div>
        </div>
        <div>
          <label>電話番号</label>
          <input id="tel1" type="text" {...register('tel1')}></input>-
          <input id="tel2" type="text" {...register('tel2')}></input>-
          <input id="tel3" type="text" {...register('tel3')}></input>
          <div className="error">{errors.tel3?.message}</div>
        </div>
        <div>
          <button type="submit">次へ</button>
        </div>
      </form >
    </>
  );
}