Is using javascript eval() safe for simple calculations in inputs?

夙愿已清 提交于 2019-12-18 05:44:23

问题


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);
}

回答1:


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 :)




回答2:


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

besides you should also add:

()%



来源:https://stackoverflow.com/questions/14020780/is-using-javascript-eval-safe-for-simple-calculations-in-inputs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!