0

I have the following regex

/(\.|\/)(gif|jpe?g|png)$/i

Which works for fileNames in ensuring on gif, jpeg and png's are accepted. However, I want to extend this code to also check fileNames and ensure they don't contain dangerous characters like

!@#$%^&*()
  1. How can I do this ?
  2. How can I "replace" these with "" ?
thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
Tom
  • 3
  • 1
  • Good source for learning regular expressions: http://www.regular-expressions.info/ – Felix Kling Sep 19 '11 at 15:33
  • possible duplicate of [Javascript string replace with regex to strip off illegal characters](http://stackoverflow.com/questions/3780696/javascript-string-replace-with-regex-to-strip-off-illegal-characters) – Felix Kling Sep 19 '11 at 15:34

3 Answers3

0

It's better to only allow a specific set of characters instead of denying every possible dangerous character, as you possibly don't know all possible dangerous characters. You know, however, all the characters you want to allow.

Use this:

/^\w+(\.|\/)(gif|jpe?g|png)$/i

This ensures that the filename contains only non-dangerous characters (letter, numbers and _).

You could also remove not allowed characters:

name = name.replace(/[^\w.]+/g, '')
Arnaud Le Blanc
  • 98,321
  • 23
  • 206
  • 194
  • Actually it works with brackets ? `/[^\w]+(\.|\/)(gif|jpe?g|png)$/i` – Tom Sep 19 '11 at 15:51
  • no, the `^` as the begining matches the begining of the string. The `\w` means *letters, numbers and _* (like [a-zA-Z_]). – Arnaud Le Blanc Sep 19 '11 at 15:52
  • hmm on image strings it doesn't appear to be working for me ? the square brackets blocks everything and without them - it allows invalid filenames ? – Tom Sep 19 '11 at 16:00
  • what kind of invalid filename does it allow ? try it here http://jsfiddle.net/gZ2cD/ – Arnaud Le Blanc Sep 19 '11 at 16:09
  • it seems to be working via http://regexpal.com/ with `/(^\w+)(\.|\/)(gif|jpe?g|png)$/i` – Tom Sep 19 '11 at 16:11
0

This regex will only match if none of the undesired characters are present

/^[^!@#\$%\^&\*\(\)]*$/
jimbo
  • 11,004
  • 6
  • 29
  • 46
0

I would actually do this separately; first use the regex to ensure the proper extension, and then plain old indexOf on each character to test for it in the string. However, you can also use a lookahead, which JavaScript supports:

/^(?!.*[!@#$%^&*()]).*(\.|\/)(gif|jpe?g|png)$/i
Justin Morgan - On strike
  • 30,035
  • 12
  • 80
  • 104