Create dynamic JavaScript validation for the if structure,

I am trying to create a dynamic check in JavaScript for the "if" structure, for example:

    var var1=1;
    var comparator="!==";
    var var2=1;
    if(var1+comparator+var2){
        alert("Yes, its false");
    }else{
        alert("Yes, its true");
    }

Three variables can be changed at the request of the user. I found that the sentence is always checked "true" because the "if" structure confirms that a string exists.

I want the user to change any of these three variables, and the function returns the result. Obviously, the comparison operator is controlled by another function that restricts the options for the operators: "===", "! ==" ...

Thank you and welcome

+3
source share
5 answers

The easiest way to do this:

eval(var1+comparator+var2)

, , . var1, var1 comparator? , . , .

, , , ANOTHER , javascript . Cross Site Scripting (XSS).

+1

, - ?

var comparator = '===';

var comparators = {
  '===': function(a, b) {
  return a === b;
  }
};

if (comparators[comparator](var1, var2)) {
  alert("Yes, its false");
}else{
  alert("Yes, its true");
}
+2

- JavaScript ; true.

if switch, .

:

var var1=1;
var comparator="!==";
//var comparator = "=="; // presumes user input, commented out in this example
var var2=1;

switch (comparator) 
{
    case "!==": 
        alert(var1 !== var2);
        break;
    case "==":
        alert(var1 == var2);
        break;
}
+1

If I understand well what you want, you can use "Function" or "eval"

var result = eval(var1+comparator+var2);

or

var result = new Function("return " + var1+comparator+var2)();
0
source

Just my approach: LIVE DEMO

function compare(a, op, b){

  var operators = {
    ">" :  a>b  ? "Great!" : "Wrong",
    "<" :  a<b  ? "Great!" : "Wrong",
    "!=":  a!=b ? "Great. Not equal!" : "Wrong"
  };
  return operators[op];

}

compare(10, ">", 20)  // Wrong
0
source

All Articles