Mathematic validator
With variables enclosed inside quiotes, e.g. "my var"
by odiseo
HTML
<form onsubmit="return false;"><input type="text" id="expression" /> <button id="evaluate">Evaluate</button></form>
JavaScript
document.getElementById("evaluate").onclick = function () {
mathEval(document.getElementById("expression").value);
}
function mathEval (exp) {
var reg = /(?:[a-z$_][a-z0-9$_]*)|(?:[;={}\[\]'!&<>^\\?:])|"([^"]+)"/ig,
valid = true;
// Detect valid JS identifier names and replace them
exp = exp.replace(reg, function ($0) {
// If the name is a direct member of Math, allow
if (Math.hasOwnProperty($0)){
return "Math."+$0;
}
else if (Math.hasOwnProperty($0.toUpperCase())){
return "Math."+$0.toUpperCase();
// Otherwise the expression is invalid
}
else if (/"([^"]+)"/.test($0)) {
console.log("we have a a nolo variable!");
console.log($0);
return true;
}
else {
console.log($0)
valid = false;
}
});
// Don't eval if our replace function flagged as invalid
if (!valid)
alert("Invalid arithmetic expression");
else
try { alert(eval(exp)); } catch (e) { alert("Invalid arithmetic expression"); };
}