How to define a regular expression to validate username with JavaScript?

Spread the love

To define a regular expression to validate username with JavaScript, we can add variuous patterns to the regex.

For instance, we write

const re =
  /^[a-zA-Z0-9](_(?!(\.|_))|\.(?!(_|\.))|[a-zA-Z0-9]){6,18}[a-zA-Z0-9]$/;

to define the re regex with various patterns.

[a-zA-Z0-9] an matches alphanumeric characters.

_(?!\.) matches a _ not followed by a .

\.(?!_) mathes a . not followed by a _

{6,18} matches minimum 6 to maximum 18 times.

Leave a Reply

Your email address will not be published. Required fields are marked *