Search code examples
javavalidationsyntaxnashorn

Using Java Nashorn engine to validate javascript only


Good morning.

I need to run javascript syntax validation through java but I'm struggling to find the best solution.

I did some tests with Nashorn using the following approach:

try
{
    ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
    Object retVal = engine.eval("findFieldValue(field);");
}
catch (ScriptException e)
{
    response.put("status", "parseexception");
    response.put("msg", e.getMessage());
}

Nashorn throws an exception saying both findFieldValue and field are undefined, which is correct. I don't need this kind of validation. All I need is to validate the syntax, like it's done by Esprima JS API

http://esprima.org/demo/validate.html

My question is. Can I ignore semantic validation with Nashorn, validating syntax only?

Thank you!


Solution

  • You are using eval() which, as you can probably guess, attempts to evaluate the expression.

    The NashornScriptEngine implements javax.script.Compilable so it provides a compile() method. To use it you would have to cast engine to NashornScriptEngine, as in

    NashornScriptEngine engine = (NashornScriptEngine) new ScriptEngineManager().getEngineByName("nashorn");
    

    You get a ScriptException if compilation fails.