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;

}

Comments

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): http://regexstorm.net/Tester.aspx?m=m&p=%5e%5c%7b%3f%5b%5cda-f%5d%7b8%7d%5c-%5b%5cda-f%5d%7b4%7d%5c-%5b%5cda-f%5d%7b4%7d%5c-%5b%5cda-f%5d%7b4%7d%5c-%5b%5cda-f%5d%7b12%7d%5c%7d%3f%24&i=936DA01F-9ABD-4d9d-80C7-02AF85C822A8&o=i

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.

Cheers.
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

String.Replace vs Regex.Replace

C# Form Application in Kiosk Mode/Fullscreen

C# using a transaction with ODBC