Search code examples
javascriptangularvalidationjmespath

input validation via JMESpath in Angular 2


So for example i have the following input:

<input type="text" name="field1" [(ngModel)]="rule['condition']">

in this input field is following input valid saleschannel.totalamount > 15. At the moment i test the validation with jmespath.search({ } , rule['condition']).

So i have following code part

<input type="text" name="field1" [(ngModel)]="rule['condition']"
[class.valid]="jmespath.search({ } , rule['condition'])"> 

The Problem with this is, if my input is not valid cause of syntax error i get an console error. So for the [class.invalid]="XXX" i need a way to catch the error, which detects for me that the input is invalid.

What can i do to achieve this or is there a better way than my attempt?


Solution

  • Got it working along time ago but forgot to answer on my own question.

    component.html

    <input type="text" (ngModelChange)="ValidateJMES($event)" [class.valid]="isValid">
    

    component.ts

    public jmespath = require('../../assets/jmespath.js');
    public valid: bool;
    
    ValidateJMES(newValue){
        try {
            this.jmespath.search({ } , newValue);
            valid = true;
    
        } catch(e) {
            valid = false;
        }
    }
    

    This way you can check if an input is a valid jmespath search expression.