Delphi check if character is in range 'A'..'Z' and '0'..'9'

23,973

An unique set of Char can be used for your purpose.

function GetValueTrat(const aValue: string): string;
const
  CHARS = ['0'..'9', 'a'..'z', 'A'..'Z'];
var
  i: Integer;
begin
  Result := aValue.Trim;
  for i := 1 to Length(Result) do
  begin
    if not (Result[i] in CHARS) then
      raise Exception.Create('Non valido');
  end;
end;

Notice that in your function if aValue contains a space character - like 'test value ' for example - an exception is raised so the usage of Trim is useless after the if statement.


A regular expression like ^[0-9a-zA-Z] can solve your issue in a more elegant way in my opinion.


EDIT
According to the @RBA's comment to the question, System.Character.TCharHelper.IsLetterOrDigit can be used as a replacement for the above logic:

if not Result[i].IsLetterOrDigit then
  raise Exception.Create('Non valido');
Share:
23,973
img.simone
Author by

img.simone

Updated on July 09, 2022

Comments

  • img.simone
    img.simone almost 2 years

    I need to check if a string contains only characters from ranges: 'A'..'Z', 'a'..'z', '0'..'9', so I wrote this function:

    function GetValueTrat(aValue: string): string;
    const
      number = [0 .. 9];
    const
      letter = ['a' .. 'z', 'A' .. 'Z'];
    var
      i: Integer;
    begin
    
      for i := 1 to length(aValue) do
      begin
        if (not(StrToInt(aValue[i]) in number)) or (not(aValue[i] in letter)) then
          raise Exception.Create('Non valido');
      end;
    
      Result := aValue.Trim;
    end;
    

    but if for example, aValue = 'Hello' the StrToInt function raise me an Exception.