skip to Main Content

I need help with making a javascript regex to validate a username. I found this regex and made some changes with the little knowledge I have

([0-9a-zA-Z]*[a-zA-Z][0-9_.-]*){3}$

but I can’t get what I want. When I try

_*2h4wk.e3

It passes in regex101.com, but it should not since it contains an asterisk

I need a regex that:

  • must have at least 3 or more alpha characters (a-zA-Z) in any order, does not have to be consecutive
  • allows numbers in any order (note: numbers are not required, but optional)
  • allows only a hyphen, underscore, and dot in any order (note: any other symbols are not allowed)
  • has min of 5 characters, max of 20

2

Answers


    • must have at least 3 or more alpha characters (a-zA-Z) in any order, does not have to be consecutive
      ([^a-zA-Z]*[a-zA-Z]){3}

    • allows numbers in any order (note: numbers are not required, but optional)
      ^[a-zA-Z0-9]*$

    • allows only a hyphen, underscore, and dot in any order (note: any other symbols are not allowed)
      ^[a-zA-Z0-9._-]*$

    • has min of 5 characters, max of 20
      ^.{5,20}$

    Resulting in /^(?=([^a-zA-Z]*[a-zA-Z]){3})[a-zA-Z0-9._-]{5,20}$/

    Login or Signup to reply.
  1. You could assert 5-20 of the allowed characters, and then match at least 3 chars a-zA-Z

    ^(?=[w.-]{5,20}$)(?:[d_.-]*[a-zA-Z]){3}[w.-]*$
    

    Explanation

    • ^ Start of string
    • (?=[w.-]{5,20}$) Assert 5-20 of the allowed characters
    • (?:[d_.-]*[a-zA-Z]){3} Match 3 times a-zA-Z followed by optional digits _ . -
    • [w.-]* Match optional word chars or . or -
    • $ End of string

    Regex demo

    const regex = /^(?=[w.-]{5,20}$)(?:[d_.-]*[a-z]){3}[w.-]*$/i;
    [
      "_*2h4wk.e3",
      "abcde",
      "_.-ab----c",
      "@#$ @2 #@$@#$",
      "........a.................b......c",
      "....a...MM"
    ].forEach(s =>
      console.log(`${regex.test(s)} --> ${s}`)
    )
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search