13

I would like to allow user to perform simple calculations in the text inputs, so that typing 2*5 will result in 10. I'm replacing everything but digits with an empty string and then make calculation using eval(). This seems easier and probably faster then parsing it manually.

It's often being said that eval() is unsafe, so I would like to hear is there any danger or drawback of using it in this situation.

function (input) {
  value = input.value.replace(/[^-\d/*+.]/g, '');
  input.value=eval(value);
}
Oskar Skuteli
  • 648
  • 6
  • 16
  • 6
    `var value` *sigh* – katspaugh Dec 24 '12 at 11:34
  • 2
    And then you'll get people asking why `2+2e-3` results in `1` instead of `2.002`. Warn the people about invalid input, don't silently throw it away. And try/catch the evaluation, so you can tell the user if it failed. – DCoder Dec 24 '12 at 11:42

2 Answers2

13

That is safe, not because you are sanitizing it, but because it's all entered by the user and run in their own browser. If they really wanted to enter malicious code, they could do it anyway by using firebug or web inspector, or even using a bookmarklet. Thankfully, there isn't much you can do maliciously with javascript except lock up your own browser :)

marcus erronius
  • 3,613
  • 1
  • 16
  • 32
1

this is safe because you are doing input validation before you put it into eval.

besides you should also add:

()%

GottZ
  • 4,824
  • 1
  • 36
  • 46
  • 4
    That's not *validation*, that's *filtering*. – DCoder Dec 24 '12 at 11:36
  • I didn't add () because 1() would cause "is not a function" error in a console and i don't like to see this; also evaluation may fail due to mismatched braces. Though probably i should use try/catch. Thanks for the modulo and exponent from the other post. – Oskar Skuteli Dec 24 '12 at 14:55