Newbie
Newbie

Reputation: 11

How to validate date in BeforePost - TField datatype

I am trying to validate the user input to ensure that the user has entered a date in the format DD/MM/YYYY before it is posted (BeforePost event) to the table in the DB and then abort if it is not.

This is for Delphi-7

This is the code I've been using

var
dateAudition : TDateTime;
begin
try
DateAudition := tblAudition.Field[4];
except
Abort;
end;
end;

I am getting an error TDateTime and Tfield are incompatible

Upvotes: 1

Views: 227

Answers (1)

Ken White
Ken White

Reputation: 125708

If your database field (column) is a DATE or DATETIME, then you don't need to do anything in OnBeforePost - the field won't allow non-date values to be stored.

The error you're getting is because TDataSet.Fields is an array of TField, and so referencing tblAudition.Fields[4] will result in a TField, and your code is trying to assign that TField to a variable you've declared as TDateTime.

If your column is not a DATE or DATETIME, and you actually do need to validate, you'll need to convert the field value (not the field itself) to the proper type first. Something like this should work:

var
  dateAudition: TDateTime;
begin
  try
    dateAudition := StrToDate(tblAudition.Fields[4].AsString);
  except
    Abort;  // This is wrong, BTW. It cancels without telling the user why
  end;
end;

Upvotes: 1

Related Questions