snekam
snekam

Reputation: 29

regex to validate user id

I want a client side validation of userid using javascript. Sample inputs are

  1. !abc
  2. abc-def , abc
  3. abc , abc-def
  4. abc
  5. abc-def_hjk

I have made a regex ([\w]*[-]?[\w]+[\s]?[,]?[\s]?)+. It matches 2,3,4,5 as needed but also matches input 1, which is invalid. Please let me know what is wrong in this regex.

Upvotes: 1

Views: 840

Answers (2)

Lion
Lion

Reputation: 45

Your problem is \w. try using a-zA-Z_ instead. this makes sure that only alphabet is used

Upvotes: 1

user2071270
user2071270

Reputation: 172

\d, \w and \s Shorthand character classes matching digits, word characters (letters, digits, and underscores), and whitespace (spaces, tabs, and line breaks). Can be used inside and outside character classes. \D, \W and \S Negated versions of the above. Should be used only outside character classes. (Can be used inside, but that is confusing.)

Upvotes: 0

Related Questions