Validating Guid

This code sample validates a given GUID using regular expressions. The IsGuid takes a string that is a global unique identifier. It checks if it fits the regular expression represented by the isGuid objects and returns a boolean value accordingly.


private static 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}$");


public static bool IsGuid(string value)
{

bool isValid = false;

if (!String.IsNullOrEmpty(value))
{
if (isGuid.IsMatch(value))
{
isValid = true;
}
}
return isValid;
}


Comments

Author: Paul28 Dec 2010 Member Level: Bronze   Points : 1

VB.Net Version (add to string library):


 Public Const GUIDRegex As String = "^(\{){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}$"

 Public Shared Function IsGUID(ByVal Expression As String) As Boolean
   Dim isValid As Boolean = False

   If Not String.IsNullOrEmpty(Expression) Then
      Dim match As System.Text.RegularExpressions.Match
      match = System.Text.RegularExpressions.Regex.Match(Expression, GUIDRegex)
      isValid = match.Success
   End If

   Return isValid
 End Function



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: