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?

More than 1 year has passed since last update.

【Zod】maxやminで文字列を正確に数える方法

Last updated at Posted at 2024-04-09

Zodの maxmin を使用すると「𩸽」などのサロゲートペアの文字は2文字としてカウントされます。

以下のように min を記述してフォームバリデーションをします。

const schema = z.object({
  name: z
    .string()
    .min(2, "2文字以上で入力してください")
})

スクリーンショット 2024-04-10 0.23.50.png

ユーザー名の入力欄には「𩸽」1文字しか入力されていないにも関わらず、「2文字以上で入力してください」というメッセージが表示されていません。

refineを使用して以下のように書き換えます。

const schema = z.object({
  name: z
    .string()
    .refine((value) => [...value].length > 2, {
      message: '2文字以上で入力してください。',
    }),
})

すると「𩸽」も1文字としてカウントされるようになり、「2文字以上で入力してください。」というエラーメッセージが表示されるようになります。

スクリーンショット 2024-04-10 0.27.18.png

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?