问题描述
我有这样的要求:
用户可以从文本框中添加公式(假设A + B),并将其保存为数据库中的公式表格及之后他可以根据此公式计算其他值,并通过适当的货币换算获得计算出的值。
如果用户输入了有效的公式,那么它是精细。但是如果用户输入(假设A + * B)无效并尝试保存它,我想向用户显示一个弹出窗口,显示这不是一个有效的公式或某事......给用户。 />
那么如何验证输入的公式?
I have a requirement like this:
User can add the formula (suppose A + B) from the text box and it is saved as a formula in the database table and later he can calculate the other values as per this formula and get back the calculated value as a result with proper currency convert.
If user entered valid formula then it is fine. but if user enter (suppose A + * B) which is invalid and try to save it, I want to show the user a pop-up showing "This is not a valid formula or something..." to the user.
So how can I validate the entered formula?
推荐答案
var isDataValid = false;
calculationFormula = calculationFormula.Formula;
<pre>calculationFormula = calculationFormula.replace(/[A-Za-z]/g, "1"); //" ----1 "
try {
var expression = eval(calculationFormula); //" ----2 "
if (isNaN(expression)) {
addErrorState(formulaTextArea, "Please enter correct formula."); //" ----3 "
isDataValid = false;
}
}
catch (e) { //" ----4 "
addErrorState(formulaTextArea, "Please enter correct formula."); //" ----3 "
isDataValid = false;
}
//"
1)用数值1替换所有字母。
2)使用jquery eval()评估
3)向用户显示错误。
4)如果尝试失败然后捕获并向用户显示错误
isDataValid =用作标志。
addErrorState()=方法用于向特定的formulaTextArea显示错误。
请注意,这是一个正确的方法。
1) Replace all the alphabets with numeric value 1.
2) evaluate with jquery eval()
3) showing error to the user.
4) if try fail then catch and show error to the user
isDataValid = use as a flag.
addErrorState() = method use to show error to particular formulaTextArea.
Please suggest, is this a correct approach.
这篇关于如何验证输入的公式是否有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!