Search code examples
liquidazure-logic-appsdotliquid

How to validate if a string property is numeric on a Logic Apps Liquid template?


I'm creating a Liquid template, and I need to validate whether a string property in my JSON payload is numeric (contains only digits).

I've tried to implement the tip suggested here

{% assign test = "A string" | plus: 0 %}
{{ test }}
{% assign test_d = "123456" | plus: 0 %}
{{ test_d }}

{{ test }} will print 1 while {{ test_d }} will print 123456. So you could do a check:

{% if test_d != 0 %}
    {{ "I'm a Int!"}}
{% else %}
    {{ "I'm a String!"}}
{% endif %}

and here.

When using assign, either of these options should give you a number:

{% assign var1 = var1 | plus: 0 %}
{% assign var2 = var2 | times: 1 %}

However, they don't seem to work the same in the DotLiquid implementation.

This is a template I've created using those tips.

{
  {% assign numValue1 = content.myDoc.myProperty | Plus: 0 %}
  {% assign numValue2 = content.myDoc.myProperty | Times: 1 %}
  {% assign numValue3 = content.myDoc.myProperty | Times: 2 %}

  {% if numValue1 != 0 %}
    "validation1": true,
  {% else %}
    "validation1": false,
  {% endif %}

  "numValue1": "{{numValue1}}",
  "numValue2": "{{numValue2}}",
  "numValue3": "{{numValue3}}"

}

However, the filter Plus: 0 concatenates the char '0' to the string, instead of behaving as described for the Ruby implementation. And Times repeats the string, instead of returning a number as suggested.

This is the output when my property is 12345

{
    "validation1": true,
    "numValue1": "123450",
    "numValue2": "12345",
    "numValue3": "1234512345"
} 

And this is the output when my property is ABC123

{
    "validation1": true,
    "numValue1": "ABC1230",
    "numValue2": "ABC123",
    "numValue3": "ABC123ABC123"
}

I know that the DotLiquid implementation is not exactly the same as the Ruby one. I've checked the source code of DotLiquid, and those filters are coded as they are behaving in my tests.

Any suggestions?


Solution

  • After going through the DotLiquid code and checking all the filters, I came up with this solution. It's not very elegant, but it does the job :)

    {
      {% assign nonNumericCharsInMyProperty  = content.myDoc.myProperty | Remove: "0" | Remove: "1" | Remove: "2" | Remove: "3" | Remove: "4" | Remove: "5" | Remove: "6" | Remove: "7" | Remove: "8" | Remove: "9" %}
    
      {%- if content.myDoc.myProperty == '' -%}
        "isValid": false,
        "message": "Invalid Message. myProperty cannot be empty."
      {%- elseif nonNumericCharsInCardNumber != '' -%}
        "isValid": false,
        "message": "Invalid Message. myProperty must be numeric."
      {%- else -%}
        "isValid": true,
        "message": ""
      {%- endif -%}
    }