Jakub
Jakub

Reputation: 2719

How to use Jexl to validate inputs in JavaScript/React?

I'm working on a project where I need to validate inputs using Jexl in a JavaScript/React application. I'm new to Jexl and I'm having trouble understanding how to use it for validation.

Specifically, I need to validate inputs against a set of rules defined in a Jexl expression. The inputs are dynamic and can change based on user interaction.

To give an example I have a form like this

form1

The visible if column is where I write the jexl syntax by opening a dialog as

dialogSave

What I'm writing here is that I have a mandatory string answer which should be always there. Then is followed by the questionKey which is the key you see under the key column. The == "yes" correspond on the items.

I know this way is valid as per jexl playground testing with a context as

{
  "answer": {
  "yes": "yes"
  }
}

What I need is to validate the input visibleIf by checking with jexl and show an error or a red borders when the syntax is invalid based on the context.

I'm not sure that is possible as I was unable to find any example of this.

Upvotes: 1

Views: 452

Answers (1)

zain ul din
zain ul din

Reputation: 629

After searching I discovered that Jexl does not have a built-in function for validating expressions. However, you can use try-catch block to validate user input and provide appropriate responses to users.

Also, in the Jexl npm page example, they handle invalid expressions using a try-catch block.

Jxel

here is how you might implement this in JavaScript code.

const isValidJexlExpression = (jexlExpression, context) => {
  try {
    const _ = jexl.evalSync(jexlExpression, context);
    return true;
  } catch (_) {
    return false; 
  }
};

// usage

if(isValidJexlExpression (/* */)) { /* TODO: show error message */ }

Upvotes: 1

Related Questions