3

When running my JavaScript through JSLint, I get the following two errors from the same line of code.

Problem at line 398 character 29: Insecure '.'.

if (password.match(/.[!,@,#,$,%,^,&,*,?,_,~,-,(,)]/))

Problem at line 398 character 41: Unescaped '^'.

if (password.match(/.[!,@,#,$,%,^,&,*,?,_,~,-,(,)]/))

I understand that JSLint may be being "over-cautious". I read the comments on a similar question, Purpose of JSLint "disallow insecure in regex" option.

Nonetheless, I would like to have the best of all worlds, and have a working regular expression that also doesn't cause JSLint to complain.

But I fail at regex.

Is it possible to make regular expression that looks for the presence of at least one special character, yet doesn't cause JSLint to complain?

Community
  • 1
  • 1
Questioner
  • 7,133
  • 16
  • 61
  • 94
  • 2
    Not directly related to your question, but you don't need all of those commas in your character class (and the dash needs to be moved to the beginning or end). If you want it to match commas, it should be `[,!@#$%^&*?_~()-]`. If not (as I expect is the case), it should be `[!@#$%^&*?_~()-]`. – Ben Blank Sep 21 '10 at 06:07
  • This is kind of unrelated, but PLEASE do not force users to include symbols in their passwords. It's just not a good idea. – 12Me21 May 26 '17 at 05:15

1 Answers1

3

That's a character class; you don't need a separator (eg: the commas). You can clean up the regex by placing the caret (^) and the dash (-) in strategic positions so they don't need to be escaped.

/[!@#$%^&*?_~()-]/

Should work. You can also use the non-word character class:

/\W/

That matches anything that's not a letter (a-zA-Z), number (0-9) or underscore (_).

NullUserException
  • 83,810
  • 28
  • 209
  • 234
  • 1
    The caret only has special meaning in a character class if it is the first character, so should not (typically) be escaped. – Ben Blank Sep 21 '10 at 06:08
  • @Ben Yeah, and you also don't have to escape the dash if it's the last character in the character class in some regex flavors. I just want to play it safe – NullUserException Sep 21 '10 at 06:11
  • Sweet. I also added in a period in the middle, like so: /[!@#$.%\^&*?_~\-()]/ because I want to let people also use a period in their password if they want. JSLint seems happy, and some quick testing indicates the code is working as expected. Thanks so much!! – Questioner Sep 21 '10 at 06:35
  • — I'd still say it's best to only use escapes where they're actually needed. Check out http://www.regexguru.com/2008/12/dont-escape-literal-characters-that-arent-metacharacters/ – Ben Blank Sep 23 '10 at 07:55