Advertisements
Home > ASP.NET > How to validate a valid GUID Value in C#

How to validate a valid GUID Value in C#


In this implementation  you pass in a Guid as an ‘out’ parameter
along with the string you want to test – it then fills in the Guid and
returns true / false depending on whether the Guid was valid…

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}$", RegexOptions.Compiled);

                                    internal static bool IsGuid(string candidate, out Guid output)

                                    {

                                                bool isValid = false;

                                                output=Guid.Empty;

                                                if(candidate!=null)

                                                {

                                               

                                                            if (isGuid.IsMatch(candidate))

                                                            {

                                                                        output=new Guid(candidate);

                                                                        isValid = true;

                                                            }

                                                }

                                                return isValid;

                                    }

This
is very useful in other Microsoft Products like Microsof Content
Management Server/SharePoint  where you use GUID quite frequently in
the API Calls.

Advertisements
Categories: ASP.NET
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: