0

I'm needing to create a dynamic validator based on a string value that's passed into a json object. So let's say you have the following string:

var required: "Homes > 0"

In this example, "Homes" is an accessible object within my function. I want to logically turn the above into:

if (this.Homes > 0) { return true; }

Thinking about this in parts:

if (this[left] > parsed[right]) { return true; }

I think you get the idea. I'm not sure if there's a way to easily extract operators without just doing a switch for every type? As in:

required: "Homes = 0" // this[Left] === 0

I'm about to do this in a very horrifying ugly string splitting way with a switch case on the operators. Was just wondering if there was a super slick way to make something like this robust.

3
  • What if instead of a string you accept a function: var required = function(o) { return o.Homes > 0; };? Commented Aug 28, 2017 at 21:41
  • Hmm. Well I'm going to try that right now. My initial goal was to make it human friendly in a string format. Commented Aug 28, 2017 at 21:43
  • You either have to write your own parser, or use someone else's. eval and the Function constructor give you access to the built–in parser. You can also insert code as the content of a script node. Take your pick. Commented Aug 28, 2017 at 23:41

2 Answers 2

1

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval

eval('Homes > 0');

but please consider using this pattern instead:

function Class(){
     this.validate = function(){
         return true;
     }
}

var x = new Class();
//overload the validate operator
x.validate = function(){
    return false;
}

You want to avoid eval because it is potentially unsafe because it allows for arbitrary code execution.

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

Comments

0

Try using

eval("if (this.Homes > 0) { return true; }");

1 Comment

eval is fundamentally insecure :(

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.