Reputation: 363
I have the following piece of code:
func GetUUIDValidator(text string) bool {
r, _ := regexp.Compile("/[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12}/")
return r.Match([]byte(text))
}
But when I pass fbd3036f-0f1c-4e98-b71c-d4cd61213f90
as a value, I got false
, while indeed it is an UUID v4.
What am I doing wrong?
Upvotes: 36
Views: 60655
Reputation: 9429
Regex is expensive. The following approach is ~18x times faster than the regex version.
Use something like https://godoc.org/github.com/google/uuid#Validate instead.
import "github.com/google/uuid"
if err := uuid.Validate("uuid..."); err == nil {
// valid UUID
}
[Jan 2025] Updated to use Validate instead of Parse, which was added in v1.5.0.
Upvotes: 110
Reputation: 1240
Since Dec 12, 2023 there is a new feature to validate directly by string: https://github.com/google/uuid/commit/9ee7366e66c9ad96bab89139418a713dc584ae29
var string anyUUID = "elmo"
err := uuid.Validate(anyUUID) // will result in an error
Live example: https://go.dev/play/p/QIzW63S0Oda
This is very useful when it comes to testing:
assert.NoError(t, uuid.Validate(anyUUID))
Upvotes: 0
Reputation: 114
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.
Upvotes: 5
Reputation: 2762
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.
Upvotes: 49
Reputation: 141
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
Upvotes: 9