Author: Tomas Rutkauskas
I want to have the user to enter a valid 24 hour time into a string field using
hours and minutes only. How do I set up a validation to make sure the user does not
enter something like 25:00 or 23:60 ?
Answer:
In order to prevent invalid entry character by character, you can use an OnKeyPress
event handler and the following as an example:
1
2 procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
3 begin
4 if not ValidEditTime(Edit1, Key) then
5 Key := #0;
6 end;
7
8 function ValidEditTime(ed: TCustomEdit; sfx: char): boolean;
9 var
10 pfx: string;
11
12 function CheckVal(const s: string; lim1, lim2: integer): boolean;
13 var
14 v: integer;
15 begin
16 v := StrToIntDef(s + sfx, lim2);
17 if Length(s) = 0 then
18 Result := (v < lim1)
19 else
20 Result := (v < lim2);
21 end;
22
23 var
24 p: integer;
25 begin
26 Result := not (sfx in ['0'..'9', ':']);
27 if (not Result) or (sfx <> #8) then
28 begin
29 pfx := ed.Text;
30 if ed.SelLength > 0 then
31 Delete(pfx, ed.SelStart + 1, ed.SelLength);
32 p := Pos(':', pfx + sfx);
33 if p = 0 then
34 Result := CheckVal(pfx, 3, 24)
35 else
36 begin
37 Result := (p = 3);
38 if Result then
39 begin
40 Result := (p > Length(pfx));
41 if not Result then
42 Result := CheckVal(Copy(pfx, p + 1, Length(pfx) - p), 6, 60)
43 end;
44 end;
45 end;
46 end;
Although the above is quite sophisticated, you will probably need an OnValidate routine as well in order to handle pasting into the control.
|