Tip: React Hook Form で Validator を実装

Tip: React Hook Form で Validator を実装

Takahiro Iwasa
(岩佐 孝浩)
Takahiro Iwasa (岩佐 孝浩)
2 min read
React

React Hook Form 用 Validator を作成しました。 React Hook Form のバリデーションルールについては、公式ドキュメントをご参照ください。

この投稿のサンプルは、 GitHub リポジトリから取得できます。

以下のコードで validators.ts を作成してください。

import { RegisterOptions } from 'react-hook-form';

export const requiredValidator = (): RegisterOptions => {
  return { required: { value: true, message: 'Must be entered.' } };
};

export const minLengthValidator = (minLength: number): () => RegisterOptions => {
  return () => ({ minLength: { value: minLength, message: `Must be ${minLength} or more characters.` } });
};

export const maxLengthValidator = (maxLength: number): () => RegisterOptions => {
  return () => ({ maxLength: { value: maxLength, message: `Must be ${maxLength} or less characters.` } });
};

export const minValidator = (min: number): () => RegisterOptions => {
  return () => ({ min: { value: min, message: `Must be ${min} or larger.` } });
};

export const maxValidator = (max: number): () => RegisterOptions => {
  return () => ({ max: {value: max, message: `Must be ${max} or smaller.` } });
};

export const emailValidator = (): RegisterOptions => {
  // Based on https://learn.microsoft.com/en-us/dotnet/standard/base-types/how-to-verify-that-strings-are-in-valid-email-format
  return { pattern: { value: /^[^@\s]+@[^@\s]+\.[^@\s]+$/, message: 'Must be a valid email.' } };
};

export const kanaValidator = (): RegisterOptions => {
  return { pattern: { value: /^[ァ-ヴ・ヲ-゚]*$/, message: 'Must be kana characters.' } };
};

export const fullWidthKanaValidator = (): RegisterOptions => {
  return { pattern: { value: /^[ァ-ヴ・]*$/, message: 'Must be full-width kana characters.' } };
};

export const halfWidthKanaValidator = (): RegisterOptions => {
  return { pattern: { value: /^[ヲ-゚]*$/, message: 'Must be half-width kana characters.' } };
};

export const composeValidators = (...validators: (() => RegisterOptions)[]) => {
  return validators.reduce((acc, cur) => ({ ...acc, ...cur() }), {});
};

必要な Validator を選択し、 composeValidators にパスしてください。

import { useForm } from 'react-hook-form';
import { composeValidators, emailValidator, requiredValidator } from './validators';

export const HelloWorldPage: React.FC = () => {
  const { register, formState: { errors } } = useForm({ mode: 'all' });
  return (
    <form>
      <input type="text" { ...register('email', composeValidators(requiredValidator, emailValidator)) } />
      <p>
        <>{ errors.email?.message }</>
      </p>
    </form>
  );
};
Takahiro Iwasa
(岩佐 孝浩)

Takahiro Iwasa (岩佐 孝浩)

Software Developer at KAKEHASHI Inc.
処方箋データ収集基盤の設計・開発・運用に携わっています。