编辑框中只有特定的数字

时间:2015-08-14 08:11:39

标签: delphi numbers pascal editbox

我希望用户只能在编辑框中编写1到49的数字。我知道如何排除字母,并且有可能只输入数字,但我不能将其限制为特定的数字(例如从1到49 - 就像彩票游戏一样)。 我将KeyDown事件添加到编辑框并输入以下代码:

   if not (KeyChar in ['1'..'9']) then
   begin
      ShowMessage('Invalid character');
      KeyChar := #0;
   end;

我该如何修改?

2 个答案:

答案 0 :(得分:3)

根据David的建议,我经常使用的模式看起来像这样:

function Validate1To49(AStr : string; var Value : integer) : boolean;
begin
  result := TryStrToInt(AStr, Value) and
            (Value >= 1) and (Value <= 49);
end;

procedure TForm1.Edit1Change(Sender: TObject);
var
  tmp : integer;
begin
  if Validate1To49(Edit1.Text, tmp) then
    Edit1.Color := clWhite
  else
    Edit1.Color := clRed;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  theValue : integer;
begin
  if Validate1To49(Edit1.Text, theValue) then begin
    // go ahead and do something with "theValue"
  end else
    ShowMessage('Value not valid');
end;   

如果用户输入任何无效的内容,则立即获得的视觉反馈不会像模态消息框那样具有侵入性。在这里,我将编辑框变为红色,但您也可以在编辑框上方显示/隐藏或更改警告标签的颜色,并附上详细说明预期输入的消息,使用绿色选中标记或其他任何看似合理的标记

这样做的好处是用户可以立即看到他们的输入是否有效。验证方法可以被包装,以便在用户尝试启动需要这些输入的操作时可以重复使用它们。在这一点上,我觉得使用模态消息框很好,因为用户明显错过了他们面前的明显线索。或者,在OnChange处理程序中进行验证时,您可以简单地禁用允许用户继续操作的任何操作控件(如按钮等)。这需要验证操作所需的所有输入控件 - 通常,您可以将整个验证操作包装到单个方法中以便合理地重复使用。

对于像整数这样的简单值,一个好的SpinEdit控件可能很有用(VCL版本包含在Samples包中 - 默认情况下并不总是安装)。上述模式更灵活,但可用于任何类型的输入。 SpinEdit不会提供任何反馈,但用户只需输入内容即可显示任何信息。如果没有关于输入元素将接受什么的明确指导,他们可能想知道应用程序是否被破坏。

答案 1 :(得分:1)

通过为编辑框编写OnKeyPress事件,也可以通过这种方式回答相同的问题。通过这种方式,用户将无法输入大于我们定义的限制的数字。

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;
相关问题