github.com/blend/go-sdk@v1.20220411.3/validate/uuid.go (about) 1 /* 2 3 Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file. 5 6 */ 7 8 package validate 9 10 import ( 11 "github.com/blend/go-sdk/ex" 12 "github.com/blend/go-sdk/uuid" 13 ) 14 15 // UUID errors 16 const ( 17 ErrUUIDRequired ex.Class = "uuid should be set" 18 ErrUUIDForbidden ex.Class = "uuid should not be set" 19 ErrUUIDV4 ex.Class = "uuid should be version 4" 20 ErrUUIDVersion ex.Class = "uuid should be a given version" 21 ) 22 23 // UUID returns a uuid.UUID validator. 24 func UUID(value *uuid.UUID) UUIDValidators { 25 return UUIDValidators{value} 26 } 27 28 // UUIDValidators implements validators for uuid.UUIDs. 29 type UUIDValidators struct { 30 Value *uuid.UUID 31 } 32 33 // Required returns a validator that an uuid is set. 34 func (u UUIDValidators) Required() Validator { 35 return func() error { 36 if u.Value == nil { 37 return Error(ErrUUIDRequired, nil) 38 } 39 if len(*u.Value) == 0 { 40 return Error(ErrUUIDRequired, nil) 41 } 42 if u.Value.IsZero() { 43 return Error(ErrUUIDRequired, nil) 44 } 45 return nil 46 } 47 } 48 49 // Forbidden returns a validator that an uuid is not set. 50 func (u UUIDValidators) Forbidden() Validator { 51 return func() error { 52 if err := u.Required()(); err == nil { 53 return Error(ErrUUIDForbidden, nil) 54 } 55 return nil 56 } 57 } 58 59 // IsV4 returns a validator that asserts a uuid.UUID is a V4 uuid. 60 func (u UUIDValidators) IsV4() Validator { 61 return func() error { 62 if u.Value == nil { 63 return Error(ErrUUIDV4, nil) 64 } 65 if len(*u.Value) == 0 { 66 return Error(ErrUUIDV4, nil) 67 } 68 if !u.Value.IsV4() { 69 return Error(ErrUUIDV4, nil) 70 } 71 return nil 72 } 73 } 74 75 // IsVersion returns a validator that asserts a uuid.UUID is a given version. 76 func (u UUIDValidators) IsVersion(version byte) Validator { 77 return func() error { 78 if u.Value == nil { 79 return Errorf(ErrUUIDVersion, nil, "version: %x", version) 80 } 81 if len(*u.Value) == 0 { 82 return Errorf(ErrUUIDVersion, nil, "version: %x", version) 83 } 84 if !u.Value.IsV4() { 85 return Errorf(ErrUUIDVersion, nil, "version: %x", version) 86 } 87 return nil 88 } 89 }