regexvalidationdelphitms-web-coredelphi-12-athens

How does regular expressions work in TMS WEB Core?


I tried doing the following regular expression function:

uses System.RegularExpressions;

...

function ValidateEmail(Email: string): Boolean;
begin
  const EmailPattern = '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$';
  Result := TRegEx.IsMatch(Email, EmailPattern);
end;

That works in VCL and FMX, but not in TMS WEB Core. It can't find the System.RegularExpressions unit:

[Error] can't find unit "System.RegularExpressions"

How can I do regular expressions using Delphi in TMS WEB Core?


Solution

  • As of v1.3.0.0 of TMS WEB Core, you're able to use regular expressions in TMS WEB Core the same way as in VCL/FMX, but from the WEBLib.RegularExpressions unit instead of System.RegularExpressions.

    So I can do the following and it works:

    uses WEBLib.RegularExpressions;
    
    ...
    
    function ValidateEmail(Email: string): Boolean;
    const
      EmailPattern = '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$';
    begin
      Result := TRegEx.IsMatch(Email, EmailPattern);
    end;
    

    If you're using an older version of TMS WEB Core, then you can also do regular expressions using JavaScript through the ASM code block in Delphi.

    Here's an example using ASM code block:

    function ValidateEmail(Email: string): Boolean;
    const
      EmailPattern = '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$';
    begin
      {$IFDEF PAS2JS}
        asm
          Result = (new RegExp(EmailPattern)).test(Email);
        end;
      {$ENDIF}
    end;