Author: Tomas Rutkauskas
How to validate input in a TEdit
Answer:
Assuming you're using regular TEdit components, during OnExit, you will see
irregular behavior from controls if you attempt to change focus at that time. The
solution is to post a message to your form in the TEdit's OnExit event handler.
This user-defined posted message will indicate that the coast is clear to begin
validating input. Since posted messages are placed at the end of the message queue,
this gives Windows the opportunity to complete the focus change before you attempt
to change the focus back to another control:
1 unit Unit5;
2
3 interface
4
5 uses
6 SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
7 Forms, Dialogs, StdCtrls, Mask;
8
9 const
10 {User-defined message}
11 um_ValidateInput = wm_User + 100;
12
13 type
14 TForm5 = class(TForm)
15 Edit1: TEdit;
16 Edit2: TEdit;
17 Edit3: TEdit;
18 Edit4: TEdit;
19 Button1: TButton;
20 procedure EditExit(Sender: TObject);
21 procedure EditEnter(Sender: TObject);
22 private
23 Refocusing: TObject;
24 {User-defined message handler}
25 procedure ValidateInput(var M: TMessage); message um_ValidateInput;
26 end;
27
28 var
29 Form5: TForm5;
30
31 implementation
32
33 {$R *.DFM}
34
35 procedure TForm5.ValidateInput(var M: TMessage);
36 var
37 E: TEdit;
38 begin
39 {The following line is my validation. I want to make sure the first character is
40 a lower case
41 alpha character. Note the typecast of lParam to a TEdit}
42 E := TEdit(M.lParam);
43 if not (E.Text[1] in ['a'..'z']) then
44 begin
45 Refocusing := E; {Avoid a loop}
46 ShowMessage('Bad input'); {Yell at the user}
47 TEdit(E).SetFocus; {Set focus back}
48 end;
49 end;
50
51 procedure TForm5.EditExit(Sender: TObject);
52 begin
53 {Post a message to myself which indicates it's time to validate the input. Pass
54 the TEdit
55 instance (Self) as the message lParam}
56 if Refocusing = nil then
57 PostMessage(Handle, um_ValidateInput, 0, longint(Sender));
58 end;
59
60 procedure TForm5.EditEnter(Sender: TObject);
61 begin
62 if Refocusing = Sender then
63 Refocusing := nil;
64 end;
65
66 end.
|