Delphi输入验证错误提示失效,TLabel重复创建问题求助
Delphi输入校验错误提示功能修复方案
问题根源分析
- 重复创建Label:原代码中
Error_Text是局部变量,每次调用Input时都会被初始化为nil,导致Assigned(Error_Text)永远为False,每次调用都会创建新的TLabel,引发资源浪费和报错。 - 显示位置错误:将错误Label的
Parent设为Edit本身,Edit的客户区域无法容纳Label,导致提示不可见;同时位置设置为Edit内部的Y=25,不符合“输入框下方显示”的需求。
修正后的代码实现
核心校验过程(支持动态创建唯一错误Label)
procedure TForm_Main.Input(Edit: TEdit; I: Integer); var Error_Text: TLabel; begin // 从Edit的Tag属性获取已关联的错误Label(避免重复创建) Error_Text := TLabel(Edit.Tag); if not Assigned(Error_Text) then begin // 首次调用时创建Label,父容器设为Edit的父控件(如Form/Panel) Error_Text := TLabel.Create(Self); Error_Text.Parent := Edit.Parent; // 设置红色字体(FMX框架写法) Error_Text.TextSettings.FontColor := TAlphaColors.Red; // 将Label定位到Edit正下方,偏移5像素 Error_Text.Position.X := Edit.Position.X; Error_Text.Position.Y := Edit.Position.Y + Edit.Height + 5; Error_Text.AutoSize := True; Error_Text.Visible := False; // 将Label指针存入Edit的Tag,后续直接复用 Edit.Tag := NativeInt(Error_Text); end; if Edit.Text.IsEmpty then begin Error_Text.Text := ''; Error_Text.Visible := False; end else begin case I of 1: begin if not TRegEx.IsMatch(Edit.Text, '^\d+$') then begin Error_Text.Text := '错误:输入只能包含数字。'; Error_Text.Visible := True; end else begin Error_Text.Text := ''; Error_Text.Visible := False; end; end; 2: begin if not TRegEx.IsMatch(Edit.Text, '^[A-Za-z]+$') then begin Error_Text.Text := '错误:输入只能包含英文字符。'; Error_Text.Visible := True; end else begin Error_Text.Text := ''; Error_Text.Visible := False; end; end; 3: begin if not TRegEx.IsMatch(Edit.Text, '^[A-Za-z0-9]+$') then begin Error_Text.Text := '错误:输入只能包含英文字符和数字。'; Error_Text.Visible := True; end else begin Error_Text.Text := ''; Error_Text.Visible := False; end; end; end; end; end;
调用代码(保持不变)
procedure TForm_Main.Edit_Code_TypeTyping(Sender: TObject); begin Input(Edit_Code_Type, 1); end;
额外注意事项
- 如果是VCL框架项目,需调整UI属性写法:
// 替换FontColor设置 Error_Text.Font.Color := clRed; // 替换Position设置为Top/Left Error_Text.Left := Edit.Left; Error_Text.Top := Edit.Top + Edit.Height + 5; - 若
Edit.Tag已被其他功能占用,建议使用TObjectDictionary<TEdit, TLabel>存储Edit与Label的映射关系,避免冲突:// 先在Form的类中声明成员变量: FErrorLabels: TObjectDictionary<TEdit, TLabel>; // Form创建时初始化: FErrorLabels := TObjectDictionary<TEdit, TLabel>.Create([doOwnsValues]); // Input过程中获取Label: if not FErrorLabels.TryGetValue(Edit, Error_Text) then begin // 创建Label并添加到字典 Error_Text := TLabel.Create(Self); // ...其他属性设置... FErrorLabels.Add(Edit, Error_Text); end;
内容的提问来源于stack exchange,提问作者Zakaria Mimeche
相关产品推荐
相关产品推荐

