Boudy hesham
Boudy hesham

Reputation: 352

problem with caret and dollar sign regex in nodejs

in node js when i try to check for validation of incoming string using express-validator it doesn't match using

check('firstName').matches('^[a-zA-Z\s\'\-$]')

to parse firstName of incoming request body

Note I've edited the question to be like

check('firstName').matches('^[a-zA-Z\s\'\-]$')

Upvotes: 0

Views: 390

Answers (2)

Boudy hesham
Boudy hesham

Reputation: 352

express was treating the string in different way than /regex/ this was the issue.

Upvotes: 0

Abdullah Danyal
Abdullah Danyal

Reputation: 1146

I see two issues here:

  • The range issue because of \-. You should use double escaping character instead.
  • The given regex will only match the first character because the quantifier is missing. You should use the + (one or more characters) quantifier at the end of the regex for full match.

The correct regex for your case would be:

check('firstName').matches('^[a-zA-Z\s\'\\-$]+')

Upvotes: 1

Related Questions