-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathmain.go
More file actions
57 lines (47 loc) · 1.2 KB
/
main.go
File metadata and controls
57 lines (47 loc) · 1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package main
import (
"errors"
"fmt"
"github.com/go-playground/validator/v10"
)
// Nullable wraps a generic value.
type Nullable[T any] struct {
Data T
}
// ValidatorValue returns the inner value that should be validated.
func (n Nullable[T]) ValidatorValue() any {
return n.Data
}
type Config struct {
Name string `validate:"required"`
}
type Record struct {
Config Nullable[Config] `validate:"required"`
}
// use a single instance of Validate, it caches struct info
var validate *validator.Validate
func main() {
validate = validator.New()
// valid case: ValidatorValue unwraps Config and Name passes required.
valid := Record{
Config: Nullable[Config]{
Data: Config{Name: "validator"},
},
}
err := validate.Struct(valid)
if err != nil {
fmt.Printf("Err(s):\n%+v\n", err)
}
// invalid case: Name is empty after unwrapping, so required fails on Config.Name.
invalid := Record{
Config: Nullable[Config]{},
}
err = validate.Struct(invalid)
if err != nil {
fmt.Printf("Err(s):\n%+v\n", err)
var validationErrs validator.ValidationErrors
if errors.As(err, &validationErrs) && len(validationErrs) > 0 {
fmt.Printf("First error namespace: %s\n", validationErrs[0].Namespace())
}
}
}