Byakugan
Byakugan

Reputation: 981

How to prevent wrong inputs (only numbers) in Delphi?

I am trying to build a function/check to prevent wrong inputs from keyboard and I am a little bit lost here.

function ReadInputs : integer;
var 
  number : integer;
begin
  repeat
    Write('Set random number (1-10): ');
    Readln(number);

    if NOT((number <= 10) AND (number >= 1)) then
      begin
        Writeln('Error! Type 1-10!');
      end;
  until (number >= 1) AND (number <= 10);
  result := column;
end;

How to prevent from any other character to be input except numbers 1-10? Why only numbers define in my function is not enough even when I set integer? When I type for example "A" it crash, so what is the right way? Thank you.

Upvotes: 2

Views: 5558

Answers (3)

Alex
Alex

Reputation: 1

Or you could use this on the OnKeyPress event:

if NOT(key in['0'..'9', #8]) then
  key := #0;

Upvotes: 0

MartynA
MartynA

Reputation: 30715

You've already had a good answerfrom David H, but a little more explanation might help.

The ReadLn() procedure dates from before applications had GUIs and doesn't really restrict what the user can type in; the user might just press [return] or type characters that aren't digits (or +/-). ReadLn(AnInteger) will succeed if what the user types happens to convert to an integer, otherwise it fails.

On the other hand, Readln(AString) will always succeed, and the problem then is just how to check that it represents an integer, and DH's answer shows you how to do that.

In case you're wondering, a GUI application, you can control what characters an edit control will accept, e.g. by using a TMaskEDit, which allows you specify what character patterns are acceptable (e.g 6 digits and nothing else) - if the user types something which doesn't match the mask, the edit control doesn't accept it. However, even if you use a TMaskEdit, it's best to check that what's been typed in actually converts to the number type you're wanting.

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 612964

As it stands your program will fail with an error if the user inputs something that cannot be converted to an integer. That's because the variable that you passed to Readln is typed as an Integer. That is effectively an assertion that the user enters a number. But you want to be more flexible than that and allow the user to recover from non-numeric input.

What you need to do is read a string. This will always succeed. Then you can decide how to handle that string. For example you would try to convert to integer, and if that succeeded, perform further validity checks.

Perhaps like this:

var
  Input: string;
  Num: Integer;
....
Readln(Input);
if TryStrToInt(Input, Num) then
  // perform checks on Num, etc.
else
  // handle error: the value input was not numeric

Upvotes: 3

Related Questions