LoginSignup
0
0

yupを使いこなしたい

Posted at

はじめに

yupについての備忘録です。
カタカナのバリデーションを実装しました。
子コンポーネントについては載せておりません。

yupについて

import * as yup from 'yup';
import { yupResolver } from '@hookform/resolvers/yup';

// バリデーションスキーマ
export const userFormSchema: yup.SchemaOf<UserForm> = yup
  .object().
  shape({
    name: yup
      .string()
      .required('名前は必須です')
      .matches(getKatakanaRegex, 'カタカナで入力してください'),
    email: yup.string().required('メールアドレスは必須です'),
});

まずはyup関数を定義します。
matches(getKatakanaRegex, 'カタカナで入力してください')では正規表現を用いてチェックしています。

以下は関数の型定義になります。

export type UserForm = {
  nameKana: string;
  email: string;
};

以下のように使用することで子コンポーネントで入力した文字に対するバリデーションが発火します。
modeのところを変えることで文字が変化したときにバリデーションを通すか、カーソルを移動させたときかを変えることができます。
これらはuseFormで操作しています。

export const SignUpUser: FC = () => {
  const methods = useForm<FormValues>({
    defaultValues: initialValues,  //yup側と一致しているとバリデーションが機能する
    resolver: yupResolver(userFormValidateSchema),
    mode: 'all', //onChange, onBlur, onSubmit, onTouched が指定可能。all → すべてのタイミングでバリデーション実行
  });

  return (
    <FormProvider {...methods}>
      <Outlet />
    </FormProvider>
  );
};

以下はパロメータの初期値です。

const initialValues: FormValues = {
  nameKana: '',
  email: '',
};

おわりに

間違っているところがあれば教えていただけると嬉しいです。

参考

https://react-hook-form.com/docs/useform
https://zenn.dev/highgrenade/articles/c378deb2ec3eea

0
0
0

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
0