1

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)

2 Answers 2

1

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?

Sign up to request clarification or add additional context in comments.

1 Comment

the expression is on the text area so he can edit and delete the items. when clicking submit button checking the value of text area should happen. ((mark1+mark2)/100)*100 is valid one. the mark1 and mark2 are not integers,it's a string also numbers can also come eg:mark1*100
0

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 {

    }
}

4 Comments

@vusam it's not working, its only working on numeric expression.
I need string expression to be validated
Ya you are right. See my edit, I think that will do the trick.
The problem with running user-supplied content through eval() is that it'd be easy for the user to accidentally break something. It's even possible that a malicious third party could exploit it, by either manipulating the field's default value or convincing the user to blindly input a malicious string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.