0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

react-hook-formでネストしたオブジェクトごとのエラー件数を取得する

Posted at
// schemaイメージ
const schema = z.object({
  fromA: z.object({
    text: z.string().max(10),
  }),
  formB: z.object({
    text: z.string().max(10),
  }),
});

/**
 * JSON.stringifyでwalkする
 */
const getFormErrorCount = (errors: FieldErrors<typeof schema>) => {
  // グループごとのエラーをmessageでカウントする
  let messageCount = 0;
  JSON.stringify(errors, (key: string, value: object) => {
    if (key === 'message') {
      messageCount++;
    }
    if (key === 'ref') {
      return undefined;
    }
    return value;
  });
}

// フォームAの文字数が溢れていたら 1が返る
getFormErrorCount(errors.fromA); // => 1
getFormErrorCount(errors.fromB); // => 0

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?