这可能是一个非常简单的问题,但我从未接触过Delphi。
我有一个编辑框,可以输入字符。但在某些特殊情况下,我必须验证编辑框中的字符是否仅为数字。
我们该怎么做呢?
注意:用户可以输入任何字符,但在验证时,我必须验证上述条件。
这可能是一个非常简单的问题,但我从未接触过Delphi。
我有一个编辑框,可以输入字符。但在某些特殊情况下,我必须验证编辑框中的字符是否仅为数字。
我们该怎么做呢?
注意:用户可以输入任何字符,但在验证时,我必须验证上述条件。
我不知道你打算使用什么事件来触发验证,但是可以像这样进行验证:
if TryStrToInt(Edit1.Text, Value) then
DoSomethingWithTheNumber(Value)
else
HandleNotANumberError(Edit1.Text);
// Taking OP question obsessively literally, this
// function doesn't allow negative sign, decimals, or anything
// but digits
function IsValidEntry(s:String):Boolean;
var
n:Integer;
begin
result := true;
for n := 1 to Length(s) do begin
if (s[n] < '0') or (s[n] > '9') then
begin
result := false;
exit;
end;
end;
end;
TryStrToInt()
。 - Johanprocedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char) ;
begin
if not(Key IN ['0'..'9', #8, #9, #13, #27, #127]) then key:= #0;
end;
这将删除任何不是数字的字符。
如果允许负数,您需要额外检查是否在输入符号“-”之前。
procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char) ;
var
Edit1Text: string;
begin
if (Key = '-') and Pos('-',Edit1.Text) = 0 then begin
Edit1.Text:= '-' + Edit1.Text; //Force the '-' to be in the front.
end
else if (Key = '-') and Pos('-',Edit1.Text) <> 0 then begin //else flip the sign
Edit1Text:= Edit1.Text;
Edit1.Text:= StringReplace(Edit1Text, '-', '',[]);
end;
if not(Key IN ['0'..'9', #8, #9, #13, #27, #127]) then key:= #0;
end;
由于用户也可以将数据粘贴到编辑框中,因此您仍需要在编辑文本更改时检查数据。
由于在ONKeyPress事件中进行这种操作会变得相当麻烦,因此我使用自定义编辑组件来进行此类检查,并防止用户将“口误”输入输入编辑框。
个人认为永远不应发出错误消息,您应始终努力不允许用户首先输入无效数据。
['0'..'9', #8, #9, #13, #27, #127, '-']
。特别是退格和删除对于输入很方便。 ;) (对于浮点数,您可能还想包括DecimalSeparator。) - NGLN