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?

/^[a-zA-Z]+$/ が分からない人へ:React Hook Form の pattern 解説

Posted at

はじめに

React Hook Form を使って入力チェックをするとき、正規表現を使うところでつまづきました。

特に「英字だけを入力させたい」という条件で、正規表現の意味が理解できず混乱…。
この記事では、私がハマった正規表現 /^[a-zA-Z]+$/ を例に、どんな意味なのか整理します。

遭遇した問題

フォームのバリデーションに以下のコードを書きました:

<Input
  {...register("userId", {
    required: "IDは必須です",
    pattern: {
      value: /^[a-zA-Z]+$/,
      message: "英字のみ",
    },
  })}
/>

一見うまく動くように見えましたが、

数字を入れるとエラー

記号を入れるとエラー

でも「なんでそうなるのか?」が分からない
という状態に。

解決方法(正規表現の解説)

/^[a-zA-Z]+$/ の1つ1つの意味を分解して考えてみます。

  • ^ → 入力の先頭を意味する

  • [a-zA-Z] → 半角の英字(小文字 a-z、大文字 A-Z)の1文字

  • + → その直前のルールを「1回以上繰り返す」

  • $ → 入力の末尾を意味する

つまりこの正規表現は:

「最初から最後まで全部が半角英字で構成されていないとエラー」

まとめ

  • React Hook Form の pattern に正規表現を渡すと入力チェックができる

  • /^[a-zA-Z]+$/ は「半角英字のみ」を許可するパターン

  • 正規表現を分解して読むと理解しやすい

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?