How to check if the string is a valid GUID?

隐身守侯 提交于 2021-01-28 15:30:32

问题


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:


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 'CLSIDFromString@ole32.dll 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;


来源:https://stackoverflow.com/questions/31717098/how-to-check-if-the-string-is-a-valid-guid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!