Delphi FMX验证EditText是否仅包含数字?

时间:2019-05-17 08:05:40

标签: delphi firemonkey delphi-10.3-rio

我需要根据Edittext.text

使用不同的过程

如果ProcessA(value: string);的前4个字符是字符串,而后4个是数字,则我需要用字符串的后4个字符的参数调用Edittext.text

如果所有8个字符都是数字,则以最后四个数字作为参数调用ProcessB(value:integer)

例如:如果EditText.TextASDF1234,那么我会打电话给ProcessA 如果EdiText.Text12345678,那么我需要打电话给ProcessB

如果字符串类似于ASD12345ASDFG1231234567A,或者数字为小数,则显示错误。

我该如何验证?

1 个答案:

答案 0 :(得分:3)

var
  Text: string;

  function CharInRange(C, FirstC, LastC: char): boolean; inline;
  begin
    Result := (C >= FirstC) and (C <= LastC);
  end;

  function IsDigitsOnly(const S: string;
    FirstIdx, LastIdx: integer): boolean;
  var
    I: integer;
  begin
    for I := FirstIdx to LastIdx do
    begin
      if not CharInRange(S[I], '0', '9') then
      begin
        Result := False;
        Exit;
      end;
    end;
    Result := True;
  end;

  function IsUpcaseLettersOnly(const S: string;
    FirstIdx, LastIdx: integer): boolean;
  var
    I: integer;
    C: char;
  begin
    for I := FirstIdx to LastIdx do
    begin
      C := S[I];
      if not CharInRange(C, 'A', 'Z') then
      begin
        Result := False;
        Exit;
      end;
    end;
    Result := True;
  end;

  procedure BadInput;
  begin
    raise Exception.Create('Bad Input');
  end;

begin
  Text := EditText.Text;
  if Length(Text) <> 8 then
  begin
    BadInput;
  end
  else if IsUpcaseLettersOnly(Text, 1, 4)
          and IsDigitsOnly(Text, 5, 8) then
  begin
    ProcessA(Copy(Text, 5, 4));
  end
  else if IsDigitsOnly(Text, 1, 8) then
  begin
    ProcessB(StrToInt(Copy(Text, 5, 4)));
  end
  else
  begin
    BadInput;
  end;
end;

或者

uses
  ..., System.RegularExpressions;

var
  Text: string;
begin
  Text := EditText.Text;
  // I know this can be done better using a
  // single regex expression with capture groups, 
  // but I don't know the correct code to do that...
  if TRegEx.IsMatch(Text, '^[A-Z]{4}[0-9]{4}$') then
  begin
    ProcessA(Copy(Text, 5, 4));
  end
  else if TRegEx.IsMatch(Text, '^[0-9]{8}$') then
  begin
    ProcessB(StrToInt(Copy(Text, 5, 4)));
  end
  else
  begin
    raise Exception.Create('Bad Input');
  end;
end;