Question

How can you check if a string is a valid GUID in vbscript? Has anyone written an IsGuid method?

Was it helpful?

Solution

This is similar to the same question in c#. Here is the regex you will need...

^[A-Fa-f0-9]{32}$|^({|()?[A-Fa-f0-9]{8}-([A-Fa-f0-9]{4}-){3}[A-Fa-f0-9]{12}(}|))?$|^({)?[0xA-Fa-f0-9]{3,10}(, {0,1}[0xA-Fa-f0-9]{3,6}){2}, {0,1}({)([0xA-Fa-f0-9]{3,4}, {0,1}){7}[0xA-Fa-f0-9]{3,4}(}})$

But that is just for starters. You will also have to verify that the various parts such as the date/time are within acceptable ranges. To get an idea of just how complex it is to test for a valid GUID, look at the source code for one of the Guid constructors.

OTHER TIPS

This function is working in classic ASP:

Function isGUID(byval strGUID)
      if isnull(strGUID) then
        isGUID = false
        exit function
      end if
      dim regEx
      set regEx = New RegExp
      regEx.Pattern = "^({|\()?[A-Fa-f0-9]{8}-([A-Fa-f0-9]{4}-){3}[A-Fa-f0-9]{12}(}|\))?$"
      isGUID = regEx.Test(strGUID)
      set RegEx = nothing
End Function

In VBScript you can use the RegExp object to match the string using regular expressions.

Techek's function did not work for me in classic ASP (vbScript). It always returned True for some odd reason. With a few minor changes it did work. See below

Function isGUID(byval strGUID)
  if isnull(strGUID) then
    isGUID = false
    exit function
  end if
  dim regEx
  set regEx = New RegExp
  regEx.Pattern = "{[0-9A-Fa-f-]+}"
  isGUID = regEx.Test(strGUID)
  set RegEx = nothing
End Function

there is another solution:

try
{
  Guid g = new Guid(stringGuid);
  safeUseGuid(stringGuid); //this statement will execute only if guid is correct
}catch(Exception){}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top