Reputation: 161
I have a numeric keypad it contains keys o to 9
, an operator keypad with different operators like +,-,/,*,<,>,=,!=,<=,>=,==
etc.
Next i have a list that contains the column names. The above requirement is to form an expression. When click the list of column names it put the value of column name in a text area box, then next selection is operator. If he want to add numeric items just click the item in numeric keypad.
My question is how can i validate the expression that the user entered in the text area is valid or not?
valid expression: ((mark1+mark2)/100)*100
valid expression:(mark1<=mark2)
invalid expression : ((mark1+5mark2)/100*100
(here a numeric value came along with column name 5mark2
, also no closing bracket)
Upvotes: 1
Views: 86
Reputation: 5331
Using instanceof and try catch
var isValid=0;
var exp='(mark1+mark2)/100*100';
try {
eval(exp);
isValid=1;
}
catch(error){
if (error instanceof TypeError) {
} else if (error instanceof ReferenceError) {
isValid=1;
} else {
}
}
Upvotes: 0
Reputation: 597
Just do the computation how you were planning to do it anyway, using a try-catch, and if it throws an error, you know that there's something wrong with it, so you can inform the user. You could do this in the background each time someone adds an item, perhaps.
Sounds easier than regex to me. Would that work?
Upvotes: 1