-6

these are the conditions for a valid username

  1. must contain a-z or A-Z
  2. can contain 0-9 anywhere
  3. must not allow any other characters

so a0 and 0a are valid user names just like username and UserName. i need a regex for this.

the issue optionally allowing 0-9

UPDATE the problem with regex like /\w+/i is it allows username like 000 but in my case it must contain an alphabet and not any special characters

Haseeb A
  • 5,356
  • 1
  • 30
  • 34

4 Answers4

1

You don't know how to compose lookahead ? just use

var isValid = /[a-zA-Z]/.test(username) && /^[a-zA-Z\d]$/.test(username);
              ^^^^^^^^^ at last one char
                                           ^^^^^^^^^^^^^only char & digits

You want to learn lookahead ? Just use:

var isValid = /^(?=.*[a-z])[a-z\d]+$/gmi.test(username);
Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
1

Maybe something like this:

/^[a-zA-z0-9]*[a-zA-z][a-zA-z0-9]*$/
Andrzej Smyk
  • 1,684
  • 11
  • 21
0

Simple solution:

/^(\d*[a-zA-Z]+\d*)+$/
kami4ka
  • 187
  • 1
  • 12
  • 1
    `[\d]` is the same as `\d`, no need for square brackets `[]`. Also there's an extra `(` at the beginning, so this is invalid – ctwheels Oct 05 '17 at 14:34
0

the working regex is /^([0-9]+[a-zA-Z]|[a-zA-Z]+[0-9]|[a-zA-Z])+$/.

it does match 0a a0 aaa

but will not match 000 or +a or a+

please read the question completely, before putting down votes

Haseeb A
  • 5,356
  • 1
  • 30
  • 34
  • I have edited my answer and posted regexp that works and is a bit simpler – Andrzej Smyk Oct 05 '17 at 14:26
  • 1
    Although this does work, the regex I put in my comment `^(?=.*[a-zA-Z])[a-zA-Z0-9]+$` will perform with an even number or fewer steps in all cases. The one that @AndrzejSmyk posted will use fewer steps in all cases as well – ctwheels Oct 05 '17 at 14:29