转载:https://blog.csdn.net/smz8023/article/details/86168052
以下是前端检验计算公式表达式的学习总结,部分代码参照以上链接,如代码有问题欢迎各位大神评论指出!
//数学公式格式校验
function formulaInfojy(formulaInfo){
var msg = "";
// 剔除空白符
formulaInfo = formulaInfo.replace(/\s/g, '');
// 错误情况,空字符串
if ("" === formulaInfo) {
msg += "<p>数学公式不能为空!</p>";
}
if (/^[\x\÷\+\-\*\/]/.test(formulaInfo)) {
msg += "<p>以运算符开头!</p>";
}
//运算符结尾
if (/[\x\÷\+\-\*\/]$/.test(formulaInfo)) {
msg += "<p>以运算符结尾!</p>";
}
//(后面是运算符或者)
if (/\([\x\÷\+\-\*\/]/.test(formulaInfo)) {
msg += "<p>(后面是运算符或者)!</p>";
}
//运算符连续
if (/[\x\÷\+\-\*\/]{2,}/.test(formulaInfo)) {
msg += "<p>运算符连续!</p>";
}
// 空括号
if (/\(\)/.test(formulaInfo)) {
msg += "<p>空括号!</p>";
}
//括号不配对
var stack = [];
for (var i = 0, item; i < formulaInfo.length; i++) {
item = formulaInfo.charAt(i);
if ('(' === item) {
stack.push('(');
} else if (')' === item) {
if (stack.length > 0) {
stack.pop();
}else{
stack.push(')');
}
}
}
if (0 !== stack.length) {
msg += "<p>括号不配对!</p>";
}
//(后面是运算符
if (/\([\x\÷\+\-\*\/]/.test(formulaInfo)) {
msg += "<p>(后面是运算符!</p>";
}
//)前面是运算符
if (/[\x\÷\+\-\*\/]\)/.test(formulaInfo)) {
msg += "<p>)前面是运算符 !</p>";
}
if(formulaInfo.indexOf("(") != -1 && formulaInfo.indexOf(")") != -1){
//(前面不是运算符
if (!/[\x\÷\+\-\*\/]\(/.test(formulaInfo)) {
if(!/^\(/.test(formulaInfo)){
msg += "<p>(前面不是运算符!</p>";
}
}
//)后面不是运算符
if (!/\)[\x\÷\+\-\*\/]/.test(formulaInfo)) {
if(!/\)$/.test(formulaInfo)){
msg += "<p>)后面不是运算符 !</p>";
}
}
}
var formulaInfoAry = formulaInfoAryJy(formulaInfo)
for (var i = 0; i < formulaInfoAry.length; i++){
var flag = false;
for (var j = 0; j < numberzdm.length; j++){
if (formulaInfoAry[i] == numberzdm[j]){
flag = true;
break;
}
}
if(flag == false){
showMsg(""+msg);
msg += "<p>字段名不存在或数据型不为数字,不能参与公式计算!</p>";
}
}
if(msg!=null && msg!=""){
showMsg("<p>当前公式校验失败!</p>"+msg);
return false;
}
return formulaInfo;
}