Validate a String to be in Guid Format in .net C#

Initially, I was using a wrong mechanism to validate a string to be in GUID format. I was doing the following:

string wrongString = String.Empty;
bool IsCorrectGuid = false;
try
{
    Guid guid = new Guid(wrongString);
    IsCorrectGuid = true;
}
catch(FormatException){}

However, try-catch is an expensive process so, if you have huge no. strings to validate and most of them will not be a Guid then, this is a very bad way of validation.

The correct way is to use Regex, and if you are working on .Net 4.0 or higher then, you can also use the Guid.TryParse method to achieve the same goal. Following I have demonstrated to validate the string in both ways.

Guid.TryParse

string correctString = Guid.NewGuid().ToString();
Guid guid;
bool guidResTrue = Guid.TryParse(correctString, out guid);

Regex

string correctString = Guid.NewGuid().ToString();

//returns true for correct format, case in-sensitive
Regex isGuid = new Regex(@"^(\{){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}$", RegexOptions.Compiled);
bool guidResTrue = isGuid.IsMatch(correctString.ToUpper());

Of course, Guid.TryParse should be the preferred way of doing it if, you’re using .Net 4.0 or higher.

One thought on “Validate a String to be in Guid Format in .net C#

  1. electronic signature FAQ April 18, 2014 / 12:46

    What I need to make a form that is signed by several people ? The information that you have posted helped me a lot as I got to know so many new and useful facts about this concept.

    Like

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.