Search code examples
delphidelphi-xefreepascallazarus

Only allow certain characters in a string


I am trying to validate a string, where by it can contain all alphebetical and numerical characters, aswell as the underline ( _ ) symbol.

This is what I tried so far:

var
  S: string;
const
  Allowed = ['A'..'Z', 'a'..'z', '0'..'9', '_'];
begin
  S := 'This_is_my_string_0123456789';

  if Length(S) > 0 then
  begin
    if (Pos(Allowed, S) > 0 then
      ShowMessage('Ok')
    else
      ShowMessage('string contains invalid symbols');
  end;
end;

In Lazarus this errors with:

Error: Incompatible type for arg no. 1: Got "Set Of Char", expected "Variant"

Clearly my use of Pos is all wrong and I am not sure if my approach is even the correct way of going about it or not?

Thanks.


Solution

  • You will have to check every single character of the string, if it's contained in Allowed

    e.g.:

    var
      S: string;
    const
      Allowed = ['A' .. 'Z', 'a' .. 'z', '0' .. '9', '_'];
    
      Function Valid: Boolean;
      var
        i: Integer;
      begin
        Result := Length(s) > 0;
        i := 1;
        while Result and (i <= Length(S)) do
        begin
          Result := Result AND (S[i] in Allowed);
          inc(i);
        end;
        if  Length(s) = 0 then Result := true;
      end;
    
    begin
      S := 'This_is_my_string_0123456789';
      if Valid then
        ShowMessage('Ok')
      else
        ShowMessage('string contains invalid symbols');
    end;