2
votes

I need to validate the user input and check if the entered string is a valid GUID. How can I do that? Is there a sort of IsValidGuid validation function?

1

1 Answers

4
votes

You can call the Windows API function CLSIDFromString and check (at its failure) if the returned value was not CO_E_CLASSSTRING (which stands for an invalid input string). Calling the built-in StringToGUID function is not reliable as it raises exception from which you're not able to get the reason of the failure.

The following function returns True if the input string is a valid GUID, False otherwise. In case of other (unexpected) failure it raises exception:

[Code]
const
  S_OK = $00000000;
  CO_E_CLASSSTRING = $800401F3;

type
  LPCLSID = TGUID;
  LPCOLESTR = WideString;

function CLSIDFromString(lpsz: LPCOLESTR; pclsid: LPCLSID): HRESULT;
  external '[email protected] stdcall';

function IsValidGuid(const Value: string): Boolean;
var
  GUID: LPCLSID;
  RetVal: HRESULT;
begin
  RetVal := CLSIDFromString(LPCOLESTR(Value), GUID);
  Result := RetVal = S_OK;
  if not Result and (RetVal <> CO_E_CLASSSTRING) then
    OleCheck(RetVal);
end;