2008. június 20., péntek
How to validate 24 hour time using a DBEdit field
Problem/Question/Abstract:
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:
procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
begin
if not ValidEditTime(Edit1, Key) then
Key := #0;
end;
function ValidEditTime(ed: TCustomEdit; sfx: char): boolean;
var
pfx: string;
function CheckVal(const s: string; lim1, lim2: integer): boolean;
var
v: integer;
begin
v := StrToIntDef(s + sfx, lim2);
if Length(s) = 0 then
Result := (v < lim1)
else
Result := (v < lim2);
end;
var
p: integer;
begin
Result := not (sfx in ['0'..'9', ':']);
if (not Result) or (sfx <> #8) then
begin
pfx := ed.Text;
if ed.SelLength > 0 then
Delete(pfx, ed.SelStart + 1, ed.SelLength);
p := Pos(':', pfx + sfx);
if p = 0 then
Result := CheckVal(pfx, 3, 24)
else
begin
Result := (p = 3);
if Result then
begin
Result := (p > Length(pfx));
if not Result then
Result := CheckVal(Copy(pfx, p + 1, Length(pfx) - p), 6, 60)
end;
end;
end;
end;
Although the above is quite sophisticated, you will probably need an OnValidate routine as well in order to handle pasting into the control.
Feliratkozás:
Megjegyzések küldése (Atom)
Nincsenek megjegyzések:
Megjegyzés küldése