views:

69

answers:

2

Hey,

I'm writing a php forms class with client and server side validation. I'm having problems checking if a literal backslash ("\") exists in a string using regular expressions in javascript.

I want to shy away from solutions other than using regex as this will reduce the amount of special cases between php and js AND reduce the amount of conditional code I need to write.

I've just been using this as an example of what a user may need in this forms class-

A password field that is a string between 6 and 12 chars long and that excludes "\","#","$","`"

I have tried:

^[^(\u0008#\$`)]{6,12}$
^[^(\b#\$`)]{6,12}$
^[^(\\#\$`)]{6,12}$

And none of them work for a backslash and I can't work out why. FYI: The latter works fine in PHP.

+3  A: 

The regular expression \\ matches a single backslash. In JavaScript, this becomes re = /\\/ or re = new RegExp("\\\\").

ripped straight from http://www.regular-expressions.info/javascript.html

drachenstern
Ah geez I'm a noob. I should of checked there first! Thanks for your help.
Josh Stuart
Thanks to @Matthew Flaschen for catching something I didn't :| /facepalm
drachenstern
@drachenstern, it's not you. It's a weird bug in StackOverflow's renderer.
Matthew Flaschen
something tells me it does escaping with a regex of its own ... but I caught that I needed to make the other two blocks ``` escaped
drachenstern
A: 

It looks like you've created a grouping of slash-hash-dollar-tick, rather than looking for any of those characters.

try this

var rgx = new RegExp(/^[^\\#\$`]{6,12}$/);
lincolnk
Thanks for your help but it wasn't the grouping. It was that I was encapsulating in quotes so either had to lose the quotes or escape as "\\\\". Appreciate your help. (S.O. just isn't letting me choose an answer yet :S)
Josh Stuart