Dynamics 365 Business Central: How to quickly check whether the value is numeric in AL

Dynamics 365 Business Central

Hi, Readers.
Today I would like to share another mini tip about Business Central, how to quickly check whether the value is numeric in AL.
First of all, there is a very convenient property in Business Central when you need to control the user to only enter numbers in the field, Numeric Property.

Numeric Property: Sets a value that requires that users enter only numbers in the field.
Applies to:

  • Table Field
  • Page Field

For example, in table 18 Customer:

This is checked before trigger OnValidate().

Your entry of ‘BC23.4’ is not an acceptable value for ‘GLN’. Only numeric characters are allowed in field.

PS: This setting is checked during validation. Validation occurs only if the field or control value is updated through the UI, for example, if a value is updated on a page or if a field is updated in a table directly. If a field is updated through application code, then the Numeric property is not validated.

And the property ‘Numeric’ cannot be customized.

So if we want to check if a value is a number in our code, is there any easy way? I had seen someone customize a function once before.
For example, this looks a little more complicated because there are decimal points to consider, such as 1.2.

Source code:

    local procedure IsNumeric(Value: Text): Boolean
    var
        i: Integer;
    begin
        for i := 1 to StrLen(Value) do
            if (Format(Value[i]) in ['0' .. '9']) or (Format(Value[i]) in ['.']) then
                if StrLen(DelChr(Value, '=', DelChr(Value, '=', '.'))) <= 1 then
                    exit(true)
                else
                    exit(false)
            else
                exit(false);
    end;

This is also a valid method, but in this post I will introduce a standard method.

In codeunit 10 “Type Helper”: procedure IsNumeric

Let’s see a simple example. Checks whether the value entered in Address 2 on the Customer Card is a number.

Great.

Very simple, give it a try!!!😁

Source code:

pageextension 50118 CustomerCardExt extends "Customer Card"
{
    layout
    {
        modify("Address 2")
        {
            trigger OnBeforeValidate()
            var
                TypeHelper: Codeunit "Type Helper";
            begin
                if TypeHelper.IsNumeric(Rec."Address 2") then
                    Message('Address 2 is numeric')
                else
                    Message('Address 2 is not numeric');
            end;
        }
    }
}

END

Hope this will help.

Thanks for reading.

ZHU

コメント

Copied title and URL