Validating a Guid in C#

Oftentimes you find a need to validate if a string is a valid Guid or not. Luckily for us .net offers some excellent regular expression tools. I've found the best way to do this is to place a small static function in a helper class that validates a string passed in using a regular expression. All regular expression stuff is location in the using System.Text.RegularExpressions namespace. So in some class simply call use the following code:

/// <summary>
/// Determines whether the specified string is GUID.
/// </summary>
/// <param name="guid">The GUID.</param>
/// <returns>
/// <c>true</c> if the specified string is GUID; otherwise, <c>false</c>.
/// </returns>
public static bool IsGuid( String guid )
if( guid != null )
return Regex.IsMatch( guid,
@"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$" );

return false;



lonekorean said…
Hi Justin. I'm a bit of a regex weenie and your post showed up on my radar, so here I am. :)

For what it's worth, you can make your regex a little shorter, and also use the "ignore case" flag.

This shows what I mean (apologies for the long URL):

The only problem is that it won't detect when you have mismatched {}. It's possible to check for this in .NET regex with a "balancing group definition", but the complexity probably isn't worth it in this case. You're better off doing a little manual string trimming/checking instead.

lonekorean said…
Sorry, this will bother me if I don't correct myself. You don't need a balancing group definition. You can check for correctly matched {} with this: GUID regex.

Popular posts from this blog

C# Form Application in Kiosk Mode/Fullscreen

C# using a transaction with ODBC

Notify Icon Text vs BalloonTipText