Title: Getting data type value in a string
Question: Frecuently we need to convert the text contained in text boxes into numeric values or perhaps dates. Here is how we can know if a string contains a valid integer, a float or a date value.
Answer:
//---------------------------------------------------------------------------
// Author : Digital Survivor [Esteban Rodrguez Nieto | Jos Plano]
// Email : plmad666@gmail.com | jose.plano@gmail
// Web site : www.ds-studios.com.ar
//---------------------------------------------------------------------------
Uses SysUtils; // Needed to call StrToIntDef and other funtions
// Miscelaneous constants used to return value types
const
IS_INVALID = -1;
IS_INTEGER = 0;
IS_FLOAT = 1;
IS_DATE = 2;
// Validating an integer value
function IsInteger(text: string) : boolean;
begin
if (StrToIntDef(text, IS_INVALID) IS_INVALID) then Result := true // A valid integer value
else Result := false; // Not a valid integer value
end;
// Validating a float value
function IsFloat(text: string) : boolean;
begin
if (StrToFloatDef(text, IS_INVALID) IS_INVALID) then Result := true // A valid float value
else Result := false; // Not a valid float value
end;
// Validating a date value
function IsDate(text: string) : boolean;
begin
if (StrToDateDef(text, IS_INVALID) IS_INVALID) then Result := true // A valid date value
else Result := false; // Not a valid date value
end;
// This function will try to convert the string to all possible data types and it will return the type
function GetType(text: string) : integer;
begin
if (StrToIntDef(text, IS_INVALID) IS_INVALID) then begin
Result := IS_INTEGER; // A valid integer value
Exit;
end;
if (StrToFloatDef(text, IS_INVALID) IS_INVALID) then begin
Result := IS_FLOAT; // A valid float value
Exit;
end;
if (StrToDateDef(text, IS_INVALID) IS_INVALID) then begin
Result := IS_DATE; // A valid date value
Exit;
end;
Result := IS_INVALID; // Not a valid integer, float or date value
end;
// I've search in this site for some example like this but I can't find any. Hope you find usefull. :)