简体   繁体   中英

How can i validate a String which includes an Expression/Condition

Hello Community!

I am looking for a way to validate an expression, like a condition in an IF block, that is stored in a string.

Example:

expression = "2 + 3 == 5"; //or "true || false == true"

if(validationFunc(expression)){
   //do something
}

...

//validates the string and returns a boolean-value
function validationFunc(str) {
   //do validation
   var regex = /^([\s()!]*(([0-9]+)|(true|false){1})[\s()]*[+\-=\*%!]*)+$/g;

   return str.match(regex);
}

There is the possiblity to validate the 'Expression-String' with Regex . I tried to make a Regex-Expression, but it seems to be more complex than i expected. In addition, I found no solution to this problem in the web.

Has somebody a solution for this problem, or is there a other way to match/validate such a string?

Valid inputs:

true
1 == true
203 == true
0 == false
true == true
true != false
(true && false) || true == true
true == (true && false) || true
20 + 40 == 60
...

Invalid inputs:

empty string
true 0
'' != 20
30 && 4 == true
20 + 3 == false
...

You could use a try ... catch statement and use the exception for an addtional return.

If wanted, you could return true (yes, it's an expression), instead of the evaluated value.

 function check(expression) { var result; try { result = eval(expression); } catch (error) { return error.toString(); } return result; } var expressions = ['30 && 4 == true', '20 + 3 == false', 'f*ck']; console.log(expressions.map(check)); 

 function isValid(expr) { try { return eval(expr); } catch { return false; } } // Valid ; Correct syntax and return true console.log(isValid(`true`)); console.log(isValid(`true == (true && false) || true`)); // Not valid console.log(isValid(`true 0`)); // Incorrect syntax console.log(isValid(`true === 0`)); // Correct syntax but returns false 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM