问题
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