Lomolo
Lomolo

Reputation: 51

Validating userName using Regex

  1. The only numbers in the username have to be at the end. There can be zero or more of them at the end.

  2. Username letters can be lowercase and uppercase.

  3. Usernames have to be at least two characters long. A two-letter username can only use alphabet letter characters.

I'm trying with this but I'm stalled. /\d+$\w+/gi

Upvotes: 4

Views: 4507

Answers (6)

This is my answer, it passed all the tests:

/^[a-z][a-z]+\d*$|^[a-z]\d{2,}$/i
  • First Part: 2 letters (or more) and zero or more numbers
  • Or
  • Second Part: 1 letter and 2 or more numbers

Upvotes: 0

Ay Jam
Ay Jam

Reputation: 1

Simplified version of /^[a-z]{2,}\d*$|(?=\w{3,})^[a-z]{1,}\d+$/i:

/^\D(\d{2,}|\D+)\d*$/i

Code explanation:

  1. ^ - start of input
  2. \D - first character is a letter
  3. \d{2,} - ends with two or more numbers
  4. | - or
  5. \D+ - has one or more letters next
  6. \d* - and ends with zero or more numbers
  7. $ - end of input
  8. i - ignore case of input

Upvotes: 0

Uglješa Ijačić
Uglješa Ijačić

Reputation: 23

You've missed cases when there's a letter in the start, followed by 2 or more numbers.

U99 = fail
d345 = fail

My solution passes these tests, as well:

/^[a-z]{2,}\d*$|(?=\w{3,})^[a-z]{1,}\d+$/i

Using positive lookahead I am making sure that in the second case there are at least 3 alphanumeric characters.

Upvotes: 0

Shashank Katiyar
Shashank Katiyar

Reputation: 139

Username having characters and digit and min 2 character long

/^[a-zA-Z]{2,}\d*$/i

Test result :

UserNam9 = pass
9username = fail
Userna99 = pass
usernameeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee = pass
Us = pass
U = fail

Upvotes: 2

Osama
Osama

Reputation: 3030

/^[A-z]{2,}[A-z0-9]{0,}$/
/^ // start of line
[A-z]{2,} //alphabet characters 2 or more
[A-z0-9]{0,} //numbers and alphabet 
$/ // end of line

Upvotes: 0

ibrahim mahrir
ibrahim mahrir

Reputation: 31712

/^[a-z]{2,}\d*$/i is:

^     : the begining
[a-z] : a character (a to z), you can add as many allowed characters as you want
{2,}  : at least 2 of them
\d*   : 0 or more digits 
$     : the end
i     : ignore case sensetivity (both lowercases and uppercases are allowed)

Upvotes: 4

Related Questions