How to validate GUID is a GUID

后端 未结 9 1783
执念已碎
执念已碎 2020-12-23 15:39

How to determine if a string contains a GUID vs just a string of numbers.

will a GUID always contain at least 1 alpha character?

9条回答
  •  南方客
    南方客 (楼主)
    2020-12-23 16:13

    There is no guarantee that a GUID contains alpha characters. FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF is a valid GUID so is 00000000-0000-0000-0000-000000000000 and anything in between.

    If you are using .NET 4.0, you can use the answer above for the Guid.Parse and Guid.TryParse. Otherwise, you can do something like this:

    public static bool TryParseGuid(string guidString, out Guid guid)
    {
        if (guidString == null) throw new ArgumentNullException("guidString");
        try
        {
            guid = new Guid(guidString);
            return true;
        }
        catch (FormatException)
        {
            guid = default(Guid);
            return false;
        }
    }
    

提交回复
热议问题