Delphi checks if a character is in the range of 'A' .. 'Z' and '0' .. '9'

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, the aValue = 'Hello'function StrToIntcalls me an Exception.

+4
source share
1 answer

A unique set Charcan 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;

Please note that in your function, if it aValuecontains a whitespace character, for example 'test value ', for example, an exception occurs, so use is Trimuseless after the instruction if.


^[0-9a-zA-Z] , .



@RBA , System.Character.TCharHelper.IsLetterOrDigit :

if not Result[i].IsLetterOrDigit then
  raise Exception.Create('Non valido');
+7

All Articles