Friday, May 20, 2005

Validate GUID's via RegEx

How to validate a valid GUID Value in C#


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 might be handy as use GUIDs a great deal in my API's.
(Souce leached so I can find it in the future by searching my blog... Original code posted on Scott Galloway's Blog)

No comments: