DEV Community

Kazutora Hattori
Kazutora Hattori

Posted on

For those who don't understand /^[a-zA-Z]+$/: React Hook Form pattern explanation

Introduction

When using React Hook Form to validate input, I ran into trouble with regular expressions.

I was particularly confused by the condition "only allow English characters to be entered." I couldn't understand the meaning of regular expressions...
In this article, I'll explain what the meaning of the regular expression /^[a-zA-Z]+$/ is, using it as an example.

Problem I Encountered

I wrote the following code for form validation:

<Input
{...register("userId", {
required: "ID is required",
pattern: {
value: /^[a-zA-Z]+$/,
message: "English characters only",
},
})}
/>
Enter fullscreen mode Exit fullscreen mode

At first glance, it seemed to work fine, but

Entering numbers resulted in an error.

Entering symbols resulted in an error.

But I still couldn't figure out why this was happening.

Solution (Regular Expression Explanation)

Let's break down the meaning of /^[a-zA-Z]+$/ and consider each part of it.

  • ^ → Refers to the beginning of the input

  • [a-zA-Z] → A single half-width English character (lowercase a-z, uppercase A-Z)

    • → Repeats the preceding rule one or more times
  • $ → Refers to the end of the input

In other words, this regular expression:

"An error occurs if the entire string is not composed entirely of half-width English characters."

Summary

  • Passing a regular expression to the React Hook Form pattern allows input validation.

  • /^[a-zA-Z]+$/ is a pattern that allows only half-width English characters.

  • Breaking down a regular expression makes it easier to understand.

Top comments (0)