Note that there are some explanatory texts on larger screens.

plurals
  1. POJSLint "eval is evil." alternatives
    primarykey
    data
    text
    <p>I am have some JavaScript functions that run on both the client (browser) and the server (within a Java Rhino context). These are small functions - basically little validators that are well defined and don't rely upon globals or closures - self-contained and portable.</p> <p>Here's an example:</p> <pre><code>function validPhoneFormat(fullObject, value, params, property) { var phonePattern = /^\+?([0-9\- \(\)])*$/; if (value &amp;&amp; value.length &amp;&amp; !phonePattern.test(value)) return [ {"policyRequirement": "VALID_PHONE_FORMAT"}]; else return []; } </code></pre> <p>To keep things DRY, my server code gets a handle on each of these functions and calls toString() on them, returning them to the browser as part of a JSON object. Something like this:</p> <pre><code> { "name" : "phoneNumber", "policies" : [ { "policyFunction" : "\nfunction validPhoneFormat(fullObject, value, params, property) {\n var phonePattern = /^\\+?([0-9\\- \\(\\)])*$/;\n if (value &amp;&amp; value.length &amp;&amp; !phonePattern.test(value)) {\n return [{\"policyRequirement\":\"VALID_PHONE_FORMAT\"}];\n } else {\n return [];\n }\n}\n" } ] } </code></pre> <p>My browser JS code then takes this response and creates an instance of this function in that context, like so:</p> <pre><code>eval("var policyFunction = " + this.policies[j].policyFunction); policyFailures = policyFunction.call(this, form2js(this.input.closest("form")[0]), this.input.val(), params, this.property.name)); </code></pre> <p>This all works very well. However, I then run this code through JSLint, and I get back this message: </p> <p><em>[ERROR] ValidatorsManager.js:142:37:eval is evil.</em></p> <p>I appreciate that often, eval can be dangerous. However, I have no idea how else I could implement such a mechanism without using it. Is there any way I can do this and also pass through the JSLint validator?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload