如何检查字符串是否为有效的GUID? [英] How to check if the string is a valid GUID?

查看:115
本文介绍了如何检查字符串是否为有效的GUID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要验证用户输入,并检查输入的字符串是否为有效的GUID.我怎样才能做到这一点?是否有一种 IsValidGuid 验证功能?

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?

推荐答案

您可以调用Windows API函数

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.

如果输入字符串是有效的GUID,则以下函数返回True,否则返回False.如果发生其他(意外)失败,则会引发异常:

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;

这篇关于如何检查字符串是否为有效的GUID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆