Search code examples
delphidelphi-2010

How to validate values that must be integer, non negative, non decimal and not a string? (Or an alphabetic word) from an InputQuery?


Im using an InputQuery to capture a value from the user, but it has to be only an integer (from 1 to 9999999...), not a decimal and not a string (not ABCDEF) or not Alphanumeric (A1B2C3) and not special chards (Hi!,). In delphi `RAD STUDIO 2010.

The scope is to capture the value and then show a message telling the user he has to input only valid values if so.

How can I accomplish that?


Solution

  • This is easy:

    var
      s: string;
      i: Integer;
    begin
    
      if InputQuery(Caption, 'Please enter a positive integer:', s) then
        if TryStrToInt(s, i) and (i > 0) then
          ShowMessage('An excellent choice, sir!')
        else
          ShowMessage('That''s not a positive integer, is it?')
    

    This will display the prompt and do nothing if the user cancels it (that's expected). On the other hand, if the user does enter a value, it is verified using TryStrToInt and a simple sign test.

    Notice that, due to boolean short-circuit evaluation, the second conjunct (i > 0) will only evaluate if the first conjunct (TryStrToInt(s, i)) evaluates to True, so we will never test an uninitialized variable i (not that it would matter in this case, though).

    You may also want to use a more sophisticated input box that automatically validates the input within the dialog itself (disclaimer: my site).


    Alternatively, you can use the InputQuery function's own validation feature, which will validate the input when the user clicks OK:

    var
      s: array of string;
      i: Integer;
    begin
      SetLength(s, 1);
      if InputQuery(Caption, ['Please enter a positive integer:'], s,
        function(const Values: array of string): Boolean
        begin
          Result := (Length(Values) = 1) and TryStrToInt(Values[0], i) and (i > 0);
          if not Result then
            ShowMessage('That''s not a positive integer, is it?')
        end)
      then
        ShowMessageFmt('You chose %d. That''s an excellent choice, sir!', [i]);