How to validate UUID v4 in Go?

In case you would be validating it as attribute of a struct, there is an awesome golang library straight from the Go called validator https://godoc.org/gopkg.in/go-playground/validator.v9 which you can use to validate all kinds of fields nested structures by provided built-in validators as well as complete custom validation methods. All you need to do is just add proper tags to the fields

import "gopkg.in/go-playground/validator.v9"

type myObject struct {
    UID string `validate:"required,uuid4"`
}

func validate(obj *myObject) {
    validate := validator.New()
    err := validate.Struct(obj)
}

It provides structured field errors and other relevant data from it.


You can utilize satori/go.uuid package to accomplish this:

import "github.com/satori/go.uuid"

func IsValidUUID(u string) bool {
  _, err := uuid.FromString(u)
  return err == nil
}

This package is widely used for UUID operations: https://github.com/satori/go.uuid


Regex is expensive. The following approach is ~18x times faster than the regex version.

Use something like https://godoc.org/github.com/google/uuid#Parse instead.

import "github.com/google/uuid"

func IsValidUUID(u string) bool {
    _, err := uuid.Parse(u)
    return err == nil
 }

Try with...

func IsValidUUID(uuid string) bool {
    r := regexp.MustCompile("^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[8|9|aA|bB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$")
    return r.MatchString(uuid)
}

Live example: https://play.golang.org/p/a4Z-Jn4EvG

Note: as others have said, validating UUIDs with regular expressions can be slow. Consider other options too if you need better performance.

Tags:

Go