Search code examples
delphivcldelphi-10.1-berlin

Delphi- Make a EditBox to accept only numbers lessthan or equal to(<=) 12 on Keypress event


I have an Edit box and am trying to make it to only accept numbers from 0 to 12. I wrote an onExit handler like this:

procedure TfrmCourse.edtDurationExit(Sender: TObject);
begin
     if not string.IsNullOrEmpty(edtDuration.Text) then
          begin
            if StrToInt(edtDuration.Text) > 12 then
            begin
              edtDuration.Clear;
              edtDuration.SetFocus;
            end;
          end;
end;

... but I want to check this while typing. The TEdit should only accept numeric input and warn when the value is > 12.

ANSWER that i propose for this question is

FINAL ANSWER

procedure TfrmCourse.edtDurationKeyPress(Sender: TObject; var Key: Char);
var
  sTextvalue: string;
begin
  if Sender = edtDuration then
  begin
    if (Key = FormatSettings.DecimalSeparator) AND
      (pos(FormatSettings.DecimalSeparator, edtDuration.Text) <> 0) then
      Key := #0;

    if (charInSet(Key, ['0' .. '9'])) then
    begin
      sTextvalue := TEdit(Sender).Text + Key;
      if sTextvalue <> '' then
      begin
        if ((StrToFloat(sTextvalue) > 12) and (Key <> #8)) then
          Key := #0;
      end;
    end
  end;
end;

Solution

  • The conversion function StrToInt() raises an EConvertError if the entered characters are not numeric. You can deal with this by setting TEdit.NumbersOnly property. I suggest to use TryStrToInt() function instead (or in addition). Although you said that you want to check while typing I also suggest using the OnChange event, because it also catches erroneous input by pasting from clipboard.

    procedure TForm5.Edit1Change(Sender: TObject);
    var
      ed: TEdit;
      v: integer;
    begin
      ed := Sender as TEdit;
      v := 0;
      if (ed.Text <> '') and
        (not TryStrToInt(ed.Text, v) or (v < 0) or (v > 12)) then
      begin
        ed.Color := $C080FF;
        errLabel.Caption := 'Only numbers 0 - 12 allowed';
        Exit;
      end
      else
      begin
        ed.Color := clWindow;
        errLabel.Caption := '';
      end;
    end;
    

    The errLabel is a label near the edit box that gives the user indication of erroneous entry.