Hi all,

I have written a program in pascal, but am having problems remembering how to validate my code, the user is asked to enter a number, but they are only allowed to enter 1,2, or 3. How do i write the code so that if any other number is entered then they will get an error message?

Please could you helkp me with this, it's driving me crazy :-P

Thanks!

Recommended Answers

All 5 Replies

Use the readln() function to get user input into a string variable. Then check the length of the string(the string should only be one character if the only numbers that are valid input are 1 2 and 3). Then check to see if that character is the ascii code of 1 2 or 3.
ex.

ReadLn(str_input);
if length(str_input) = 1 then
begin
    if str_input = '1' or str_input = '2' or str_input = '3' then
    begin
        do_stuff(str_input);
    end;
    
end else
begin
    do_otherstuff();
end;

Thank you very much, I'm guessing this is the only way? I ask that because I have another part to validate, which is 1-35 instead of just 1,2,3. Meaning i have to type..

if str_input = '1' or str_input = '2' or str_input = '3'... all the way up to 35? time comsuming... >.< lol.

For that you would check to see if the string has a length of 1 or 2. Then you would iterate over the string and make sure each character of the string is a numeric ascii code(48 to 57 I believe...). Check your ascii values on an ascii table somewhere.

var 
    s : string;
    i, e: integer;
begin
    s := '6';
    val(s, i, e); 
    if i < 35 then //or whatever value you want
       do_something
    else do_something_else;
end.

I'm not sure if the val function exists in (Borland/Turbo) Pascal, i compiled this code in Delphi.

Cheers,
Ionut

for disable input other digit, for TEdit.OnKeyPress:

procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
begin
  if not (Key in ['1','2','3']) then Key := #0;
end;

or, for check range:

function ValueInRange(const Val: string; const Min,Max: integer): Boolean;
begin
  Result := (Trim(Val) <> '') and ((Val >= IntToStr(Min)) and (Val <= IntToStr(Max)));
end;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.