github.com/blend/go-sdk@v1.20220411.3/validate/many.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 ) 13 14 // Errors 15 const ( 16 ErrSomeNil ex.Class = "all references should be nil" 17 ErrSomeNotNil ex.Class = "at least one reference should not be nil" 18 ErrSomeOneNotNil ex.Class = "exactly one of a set of reference should not be nil" 19 ) 20 21 // Many defines validator rules that apply to a variadic 22 // set of untyped references. 23 func Many(objs ...interface{}) ManyValidators { 24 return ManyValidators{Objs: objs} 25 } 26 27 // ManyValidators returns the validator singleton for some rules. 28 type ManyValidators struct { 29 Objs []interface{} 30 } 31 32 // Nil ensures none of a set of references aren't nil. 33 func (mv ManyValidators) Nil() Validator { 34 return func() error { 35 for _, obj := range mv.Objs { 36 if !IsNil(obj) { 37 return Error(ErrSomeNil, nil) 38 } 39 } 40 return nil 41 } 42 } 43 44 // NotNil ensures at least one reference is set. 45 func (mv ManyValidators) NotNil() Validator { 46 return func() error { 47 for _, obj := range mv.Objs { 48 if !IsNil(obj) { 49 return nil 50 } 51 } 52 return Error(ErrSomeNotNil, nil) 53 } 54 } 55 56 // OneNotNil ensures at least and at most one reference is set. 57 func (mv ManyValidators) OneNotNil() Validator { 58 return func() error { 59 var set bool 60 for _, obj := range mv.Objs { 61 if !IsNil(obj) { 62 if set { 63 return Error(ErrSomeOneNotNil, nil) 64 } 65 set = true 66 } 67 } 68 if !set { 69 return Error(ErrSomeOneNotNil, nil) 70 } 71 return nil 72 } 73 }