DebugPointer
Published on

Regex for Username validation

Regex for Username validation

A username is a unique identifier chosen by a user to identify themselves on a computer system or online service. It is often used in combination with a password to authenticate a user and grant them access to certain features or information. Usernames are typically used on websites, email services, and other online platforms, as well as on local computer systems that use a login system or website. In this article let's understand how we can create a regex for username and how regex can be matched for a valid username.

Regex (short for regular expression) is a powerful tool used for searching and manipulating text. It is composed of a sequence of characters that define a search pattern. Regex can be used to find patterns in large amounts of text, validate user input, and manipulate strings. It is widely used in programming languages, text editors, and command line tools.

Structure of Strong Username

  • It should have atleast 6 characters and maximum of 30 characters
  • It should have atleast 1 alphabet
  • It can optionally have underscore _
  • No special characters are allowed

Regex for checking if username is valid

Regular Expression-

For a username containing minimum 6-30 characters, with at least 1 letter-

/^\w{6,30}$/gm

Test string examples for the above regex-

Input StringMatch Output
$%^&abcabcabcdoes not match
rocky_starmatches
34212does not match
iamyoumatches

Here is a detailed explanation of the above regex-

/^\w{6,30}$/gm

^ asserts position at start of a line
\w matches any word character (equivalent to [a-zA-Z0-9_])
{6,30} matches the previous token between 6 and 30 times, as many times as possible, giving back as needed (greedy)
$ asserts position at the end of a line
Global pattern flags
g modifier: global. All matches (don't return after first match)
m modifier: multi line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)

Hope this article was useful to match valid username regex pattern.