ASP.NET C#: Test whether a string is a GUID
Often it is useful to check whether or not a string is actually a Guid, especially useful if you pass guid querystrings between pages to identify things like users, videos or blogs etc.
One way you could do this is to user a try catch around a new Guid(String) statement but its bad practice to use a try catch for this purpose. The way I like to check that a string is actually a guid is by using a regular expression. The following code is a helper method that uses this regular expression from RegexLib to test for a Guid:
Boolean IsGuid(string expression)
{
if (expression != null)
{
Regex guidRegEx = new Regex(@"[({]?(0x)?[0-9a-fA-F]{8}([-,]?(0x)?[0-9a-fA-F]{4}){2}((-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{12})|(,\{0x[0-9a-fA-F]{2}(,0x[0-9a-fA-F]{2}){7}\}))[)}]?");
return guidRegEx.IsMatch(expression);
}
return false;
}
I use this method in one of two place:
- In a class that inherits from System.Web.UI.Page. All pages in my application then inherit from this class.
- As a static method in a common class. This means that this IsGuid method can be called from anywhere without the need for an object declaration.
This method could be easily modified to check for other datatypes, not just Guids, for example integers or email addresses.
One Response to ASP.NET C#: Test whether a string is a GUID
Leave a Reply Cancel reply
-
Calendar
May 2012 M T W T F S S « Mar 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 -
Meta






Use Guid.TryParse is another Option and Short Way to resolve the Issue