LoginSignup
13
3

More than 1 year has passed since last update.

React Hook Form,バリデーションzodを使用した場合の重複チェック

Posted at

はじめに

React Hook Form を使用し、バリデーションライブラリはzod という案件にて、重複チェックが必要だったのでそのメモです。
私が探した時点(2022.08)では、日本語で解説してくれている記事を見つけることができなかったので、参考になれば嬉しいです。

最初に

React Hook Formでバリデーションライブラリはzodを使用する方法は他の方が丁寧に書かれているので、敢えて書きません。

やりたいこと

zodを使用して、アプリ名の重複チェックをしたい

結論

zodはz.object内にバリエーションルールを記載するのですが、

index.ts
    .refine

refineを使用すれば良さそうです。

index.ts

const FROM_SCHEMA = useMemo(() => {
    return z.object({
      name: z
        .string()
        .min(1)
        .refine(
          (name: string) =>
            !(apps && apps.some((app: AppSchema) => app.name === name)),
          {
            message: 'すでに同じ名前のアプリが存在します',
          }
        ),
    })
  }, [apps])

const {
    handleSubmit,
    register,
    reset,
    formState: { errors },
  } = useForm<z.infer<typeof FROM_SCHEMA>>({
    mode: 'onSubmit',
    resolver: zodResolver(FROM_SCHEMA),
    defaultValues: { ...template },
  })


参考

13
3
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
13
3