0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【React】バリデーション付きフォーム

Posted at

はじめに

 本記事は、プログラミング初学者が、学習を進めていて疑問に思った点について調べた結果を備忘録も兼ねてまとめたものです。
 そのため、記事の内容に誤りが含まれている可能性があります。ご容赦ください。
 間違いを見つけた方は、お手数ですが、ご指摘いただけますと幸いです。

バリデーション付きフォーム

npm i react-hook-formでreact-hook-formを導入

.tsx

import React from 'react'
import { useForm } from 'react-hook-form'

const numberRegExp = /^[0-9]+$/

type FormState = {
  firstName: string
  lastName: string
  age: number
}

type Props = {}

export const Example2WithRHF: React.FC<Props> = () => {
  const { register, handleSubmit, reset, errors } = useForm<FormState>({
    mode: 'onChange',
    defaultValues: {
      firstName: '',
      lastName: '',
      age: 18,
    },
  })

  const onSubmit = handleSubmit((data) => {
    console.log(data)
  })

  return (
    <div>
      <form onSubmit={onSubmit}>
        <div className="flex-column">
          <span>first name</span>
          <input
            name="firstName"
            type="text"
            ref={register({
              required: '必須項目です',
              maxLength: {
                value: 20,
                message: '20文字以内で入力してください',
              },
            })}
          />
          <span className={styles['error-message']}>
            {errors.firstName?.message}
          </span>
        </div>
        <div className="flex-column">
          <span>last name</span>
          <input
            name="lastName"
            type="text"
            ref={register({
              required: '必須項目です',
              maxLength: {
                value: 20,
                message: '20文字以内で入力してください',
              },
            })}
          />
          <span className={styles['error-message']}>
            {errors.lastName?.message}
          </span>
        </div>
        <div className="flex-column">
          <span>age</span>
          <input
            name="age"
            type="number"
            ref={register({
              valueAsNumber: true,
              required: '必須項目です',
              pattern: {
                value: numberRegExp,
                message: '整数で入力してください',
              },
              min: {
                value: 18,
                message: '18以上の数字を入力してください',
              },
              max: {
                value: 100,
                message: '100以下の数字を入力してください',
              },
            })}
          />
          <span className={styles['error-message']}>{errors.age?.message}</span>
        </div>
        <button type="button" onClick={() => reset()}>
          リセット
        </button>
        <button>送信</button>
      </form>
    </div>
  )
}
0
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?