Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate UUID v4 in Go?

Tags:

go

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?

like image 219
Roberto Santelices Avatar asked Aug 30 '25 15:08

Roberto Santelices


1 Answers

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.

like image 132
mattes Avatar answered Oct 14 '25 02:10

mattes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!