skip to Main Content

I want to write a RegEx for username validation. Username must be more than 6 characters and start with a letter(uppercase or lowercase), but in the following, you can use letters, numbers, dot or underscore. The point is that the use of dot and underscore is optional, but if you decide to use them, you have the right to write them only once, if it is used twice or more, then the username is wrong. For example:

jamesbrianquinn     //ture
james.brianquinn    //true
james.brian_quinn   //true
james.brian.quinn   //false
james_brian_quinn   //false
james.brian__quinn  //false

The location of the dot and underscore is not important. The only important thing is that they should not be the first letter of the username or repeated more than once.

I tried to write RegEx by using "?" for dot and underscore in the character set, but it didn’t work for me:

/^[a-zA-Z][a-zA-Z0-9.?_?]+$/g

So, what is the correct RegEx???

2

Answers


  1. You could use negative lookaheads to enforce a maximum of one dot or underscore:

    ^(?!.*..*.)(?!.*_.*_)[A-Za-z][A-Za-z0-9._]{5,}$
    

    This pattern says to match:

    • ^ start of the username
      • (?!.*..*.) assert that two dots do not appear (= max one dot)
      • (?!.*_.*_) assert that two underscores do not appear (= max one _)
      • [A-Za-z] first character is letter
      • [A-Za-z0-9._]{5,} five or more following valid characters
    • $ end of the username
    Login or Signup to reply.
  2. Using a single lookahead, a backreference and a case insensitive flag /i

    ^[A-Z](?!.*([._]).*1)[A-Z0-9._]{5,}$
    

    The pattern matches:

    • ^ Start of string
    • [A-Z] Match a single char A-Z
    • (?!.*([._]).*1) Negative lookahead, assert not 2 times either . or _ a capture group ([._]) and a backreference to match the same character with a backreference 1
    • [A-Z0-9._]{5,} Match 5 or more times a char A-Z 0-9 . or _
    • $ End of string

    Regex demo

    const regex = /^[A-Z](?!.*([._]).*1)[A-Z0-9._]{5,}$/i;
    [
      "jamesbrianquinn",
      "james.brianquinn",
      "james.brian_quinn",
      "james.brian.quinn",
      "james_brian_quinn",
      "james.brian__quinn"
    ].forEach(s =>
      console.log(`${s} --> ${regex.test(s)}`)
    );
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search