Delphi Programming – Validating Date Fields

When using Delphi data controls to enter data into a form, one problem that can pop up, is invalid entries causing the program to bomb / error out.

For instance if a user is supposed to enter a date and they enter 99/99/99, the program will display the message “99/99/99 is an invalid date” and exit. We don’t want that! A similar error can occur with floating point fields (though less often).

There is some discussion of this problem in various forums online, but I found no simple, easy to apply solutions. So, I created a simple and elegant one.

The validation is applied to the data fields onsettext event. The 2 data types that were giving me problems were tDate and tFloat. I wrote two functions to handle the validation for these types of fields (val_date and val_float). I also wrote another function that will automatically apply these validation functions, when passed a database object.

procedure tmain.val_date( sender : tfield; const text : string);
var
chk_dt : tdatetime ;
begin
// used in a date fields onset text event
// test for a valid date entry
if not ( trystrtodate( text, chk_dt ) ) then
begin
showmessage( ‘Invalid date entered.’ );
(sender as tdatefield ).Value:= hbc.date;
abort;
end;
// date entered is OK, save to the database field
( sender as tdatefield).AsString:= text;
end;

procedure tmain.val_float( sender : tfield; const text : string );
var
f_val : string;
f_float : double;
err : integer;
begin
// used in a float fields onsettext event
//f_val:= ed_wchk.Text;
f_val:= text;
val( f_val, f_float, err );
if ( err <> 0 ) then
begin
showmessage( f_val + ‘ is not a valid number.’ );
( sender as tfloatfield ).Value := 0.00;
abort;
end;
(sender as tfloatfield ).Value:= f_float;
end;

procedure tmain.set_val( dbname : ttable );
var
mfld : tfield;
mfcnt : integer;
begin
// goes through a dbfs fields and sets settext handler to val_float, val_date
// for date or float fields
for mfcnt:= 0 to dbname.FieldCount – 1 do
begin
mfld:= dbname.Fields[ mfcnt ];
if ( mfld.DataType = ftFloat ) then
mfld.OnSetText:= val_float;
if ( mfld.DataType = ftDate ) then
mfld.OnSetText:= val_date;
end;

end;

If you found this article useful, or if you have corrections or improvements to make, please email me via my contact form.

Leave a Reply