Specific validation of dates using TryStrToDate

Alex Gorski picture Alex Gorski · Oct 9, 2013 · Viewed 7.9k times · Source

I'm trying to validate dates entered by the user using TryStrToDate to ensure that they can be properly displayed on the screen of the application I'm working on, but don't know exactly how it all works. I want to be able to return False when a valid date that isn't exactly 10 characters in length is entered.

For example, 09/02/2012 would return True, but 09/2/2012 or 9/02/2012 would return False.

I wanted to keep this simple so I've only been interested in using TryStrToDate, but if there is another built in function that does this then that would be just as good. The data entered by the user is validated on entry to only allow a 10 character date.

Because of this I am currently using something like:

var
  tempStr: string;
  tempDate: TDateTime;
  fs: TFormatSettings;
  error: Boolean;
  count: Integer;
begin
  tempStr := '09/2/2012'; //example of a date that should be rejected.
  GetLocaleFormatSettings(2048, fs);
  error := not TryStrToDate(tempStr, tempDate, formatSettings);
  if not error then
  begin
    error := True;
    if Length(tempStr) = 10 then
    begin
      count := Length(tempStr) - Length(StringReplace(tempStr, '/', '',   [frReplaceAll]));
      error := not (count = 2);
    end
  end
end

Which works just fine, but there is also an instance of data being imported from a .csv file through XML which could have any sort of format to it.

My current solution still seems to work, but I was wondering if there was a way to minimize the processing by just using TryStrToDate and having it only accept valid dates in the 10 character format that I require. I've tried manually setting the shortdate format:

fs.ShortDateFormat := 'mm/dd/yyyy';

but TryStrToDate always accepts valid dates, even if they aren't exactly 10 characters in length.

My Ideal solution would be to keep it to something like:

error := not TryStrToDate(tempStr, tempDate, fs);

Just wondering if that is possible using TryStrToDate or some other delphi function.

Any help is greatly appreciated!

I'm using Delphi 7 by the way.

Answer

Dale M picture Dale M · Oct 9, 2013

Create this function:

function IsValidDateCheck(const AValue: String): Boolean;
var
  dtTemp: TDateTime;
begin
  Result := False;

  if Length(AValue) = 10 then
    if (AValue[3] = '/') and (AValue[6] = '/') then
      Result := TryStrToDate(AValue, dtTemp);
end;

Example usage:

if IsValidDateCheck(tempStr) then
  ShowMessage(tempStr + ' is a valid date.')
else
  ShowMessage(tempStr + ' is not a valid date.');