Skip to main content
10-Marble
Mar 13, 2024 4:36 AM UTC
Question

Validate service response using validator

HI, I am starting with Thingworx. I have a query as I am getting service response as jsonarray and i want to validate one parameter of each object in Jsonarray. how to do that using validator. i tried to create one parameter in validator and using expression i am validating it but validator is called for first object of array and it validates the first object only but how to validate the remaining items in Array? Appriciate help in advance. 

Thanks.

5 replies

16-Pearl
Mar 13, 2024 11:48 AM UTC

Hi @DeepakParihar  Look at the below reference post, and let us know if you have any doubts.

https://community.ptc.com/t5/ThingWorx-Developers/Validator-Function-is-not-working-as-expected/m-p/928723#M65421

Translate
10-Marble
Mar 22, 2024 10:28 AM UTC

its works for first object of json array. but how to get all response of service and validation each object using validator. i have seen loops are not supported in validator expressions.

Translate
14-Alexandrite
Mar 14, 2024 2:58 AM UTC

So If i get it correctly, you want to validate the JSON array inside the validator? You might use a loop and test if either all of the objects are valid or one of them is invalid and so on.

 

If you want to validate individual object and return valid/invalid for each object in runtime, that might not be possible, as the length might be dynamic, unless you have a static array of objects.

Translate
10-Marble
Mar 22, 2024 10:28 AM UTC

Loops are not allowed in validator expression.

Translate
15-Moonstone
Mar 27, 2024 7:19 AM UTC

If you pass the JSON in the Validator you can loop through it.

 

I am using a simple hardcoded Array in this example, but I think a JSON object should work the same way.

 

let arr = [1, null, 3];
let hasInvalidElements = (testArr) => testArr.some((element) => element === null);

Output = hasInvalidElements(arr);

 

In this case I am using the "some" Method to check if there are "null" values inside the array. This method will stop iterating as soon as the provided function (element === null) returns true for an element. So no further unnecessary iteration.

Translate