I need to accept a string from a user.
Something like (2*34)+96/2*6-98
and not an illegal string like 4*(2*aggw*^^)*as.,,;
I need to verify if it is a valid arithmetic equation.
I need to accept a string from a user.
Something like (2*34)+96/2*6-98
and not an illegal string like 4*(2*aggw*^^)*as.,,;
I need to verify if it is a valid arithmetic equation.
I'd set up a function that checks for the following:
*^
, -)
, and +/
, while allowing other unspecified combinations (such as ((
,--
,+(-(
)Infinity
keyword) values between specified, allowable operatorsdocument.querySelector("input").addEventListener("keyup", function() {
document.getElementById("output").innerHTML = isValid(this.value);
});
function isValid(str) {
var invalidOperatorPairs = ["**", "*/", "/*", "//", "()", "^^", "^/", "/^", "^*", "*^", "-)", "+)", "*)", "/*", "^)", "-*", "-/", "-^", "+*", "+/", "+^", "(*", "(/", "(^","/)","*)","+)","-)","^)"]
str = "(" + str + ")";
var open = 0;
for (var i = 0, len = str.length; i < len; i++) {
var curr = str[i];
if (curr === "(") {
open += 1;
} else if (curr === ")") {
open -= 1;
if (open < 0) {
return false
}
}
if (i > 0) {
for (var j = 0, oplen = invalidOperatorPairs.length; j < oplen; j++) {
if (str[i - 1] == invalidOperatorPairs[j][0] && curr == invalidOperatorPairs[j][1]) {
return false
}
}
}
}
if (open !== 0) return false;
var sections = str.split(/[\+\-\*\/\^\)\(]/g);
for (i = 0, len = sections.length; i < len; i++) {
if ((sections[i].length > 0) &&
!(Number(sections[i]) !== NaN && isFinite(sections[i]))) {
return false
}
}
return true;
}
<input type="text" value="" />
<div id="output"></div>
You can use regex in javascript to do so: For example:
var op1= "(2*34)+96/2*6-98";
var op2 = "4*(2*aggw*^^)*as.,,;";
//Regular expression to use
var regEx = /([-+]?[0-9]*\.?[0-9]+[\/\+\-\*])+([-+]?[0-9]*\.?[0-9]+)/g;
//Following will be true
alert(regEx.test(op1));
//Following will be false
alert(regEx.test(op2));
You can probably find better matching regular expression. I found this one here .