-2

I need to validate Username for an user for below condition.

  • username can contain letters, numbers or combination of both.
  • Username must not contain any special characters such as @ $ % ^ & * () + = ‘ ~ - _"

Valid Examples: Test123

123Test

T123est

Invalid Examples:

Test@%^&123

@#$Test

Test123@#$%^

Below is the expression I tried:

/[a-zA-Z\d]+/

/[^@$%^&()+=‘~-_"]/

1 Answers1

0

This should do it:

/^[A-Za-z\d]+$/

^ and $ marks, start and end of string and are needed to not match part of the input.

Edit: Updated as commenters suggested as I didn't remember that underscore was part of \w

Fredrik C
  • 570
  • 6
  • 22
  • 2
    I suppose a valid username cannot be empty though. Also note that `\w` is shorthand for `[A-Za-z0-9_]`, so includes digits **and** the underscore. I think you need `^[A-Za-z\d]+$`. – JvdV Jan 12 '21 at 08:56
  • Or \b[\w-[_]]+\b to check "words" rather than complete segments – TonyR Jan 12 '21 at 13:29