admin管理员组文章数量:1287578
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);
}
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);
}
Share
Improve this question
asked Dec 24, 2012 at 11:29
Oskar SkuteliOskar Skuteli
6587 silver badges16 bronze badges
2
-
6
var value
sigh – katspaugh Commented Dec 24, 2012 at 11:34 -
2
And then you'll get people asking why
2+2e-3
results in1
instead of2.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. – user1233508 Commented Dec 24, 2012 at 11:42
2 Answers
Reset to default 13That 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 :)
this is safe because you are doing input validation before you put it into eval.
besides you should also add:
()%
本文标签: Is using javascript eval() safe for simple calculations in inputsStack Overflow
版权声明:本文标题:Is using javascript eval() safe for simple calculations in inputs? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741294771a2370752.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论