delphi Text,combox 输入框的统一验证

防止用户误输入是软件开发的一项必不可少的工作,除才之外,还要为用户的使用提供最大方便。当然,我们可以利用或开发新的组件,以完成这些功 能。但是,在团队开发中,每个成员都用自己认为不错的组件开发自己所承担的模块,会给软件的后期维护带来麻烦。交工的时候,项目负责人可不买你的帐。如果 你用函数调用来完成这些功能,老盖也管不着。下面就是针对常用delphi组件的限制用户输入函数。
(一)TEdit、TDBEdit、TComboBox、TDBComboBox的输入
分三种类型限制:
(1)任意输入
(2)整数输入
(3)浮点数输入
限制的项目如下:
(1)整数输入只能输入数字0-9、+、-
(2)浮点输入只能输入数字0-9、+、-、.
(3)+和-只能有其一,并且只能出现在最前面
(4).只能有一个
(5)限制小数位数
函数如下:

procedure MxFormatKeyPress(Text:string; SelStart,SelLength:integer;
                           var Key:Char; EditType:integer; Digits:integer);
begin
{--------------------------------------------过滤字符--------------------------}
  {ESC/BackSpace键 或 任意输入时退出}
  if (Key= #27) or (Key= #8) or (EditType= 1) then exit;

  if EditType= 2 then
     if not (Key in ['0'..'9','+','-']) then
     begin
       Key:=#0;
       Exit;
     end;

  if EditType= 3 then
     if not (Key in ['0'..'9','+','-','.']) then
     begin
       Key:=#0;
       Exit;
     end;
{--------------------------------------------控制+- ---------------------------}
  {+-只能在第一个位置}
  {1、存在
   2、不存在
   3、选择
   4、不选择}
  if (Key = '-') or (Key = '+') then
  begin
    if ((Pos('-',Text) > 0) or (Pos('+',Text) > 0)) and (SelLength= 0) then
       Key:= #0;
    if SelStart > 0 then Key:= #0;
  end;
{------------------------------------------------------------------------------}
  {控制.}
  if (Key = '.') and (EditType=3) then
  begin
    if (Pos('.',Text) > 0) and ( (Pos('.',Text)< SelStart)or(Pos('.',Text) > (Selstart+SelLength)) ) then
       Key:= #0;
    if SelStart = 0 then Key:= #0;
  end;
{------------------------------------------------------------------------------}
//验证小数 位置
  if (Digits>0) and (SelStart+SelLength > 0) and (EditType=3) then
     if (pos('.',Text )>0 ) and (SelStart>=pos('.',Text)) then
        if length(Text)-pos('.',Text )>=Digits then
           Key:=#0;
end;

 

此函数在所限制组件的OnKeyPress事件中调用。Key即为OnKeyPress携带的Key:Char参数;EditType为限制的类 型:1-任意输入;2-整数输入;3-浮点输入;Digits为浮点数输入时小数的位数,如果是零,则可输入任意位数。另外,此函数只适用于有Text、 SelStart、SelLength等属性的TWinControl类的派生类。

具体限制各组件的二级函数如下:

限制TEdit、TDBEdit:
procedure MxFormatEditKeyPress(Edit:TCustomEdit;var Key:Char;EditType:integer;
        Digits:integer);
begin
  MxFormatKeyPress(Edit.Text,Edit.SelStart,Edit.SelLength,Key,EditType,Digits);
end;

限制TComboBox:
procedure MxFormatComboKeyPress(Combo:TComboBox;var Key:Char;EditType:integer;
        Digits:integer);
begin
  MxFormatKeyPress(Combo.Text,Combo.SelStart,Combo.SelLength,Key,EditType,Digits);
end;

转载于:https://www.cnblogs.com/cnby/p/4597028.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值