0

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!

1
  • 1
    wrap it in an function? Commented Aug 3, 2018 at 17:35

1 Answer 1

5

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.

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

3 Comments

No there is not such method. Why is this accepted answer ?
@kasper Actually, the Nashorn script engine does implement Compilable, so it does have a compile() method. I agree this is not obvious in the example provided by the OP, as engine would need to be casted to NashornScriptEngine to work. I've updated the answer. Thanks.
yeah, that seems true after your answer i also looked into it. We can use something like compilable = (Compilable) scriptEngine; compilable.compile(script);. Thanks for update on answer

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.