Validate
Use field tags for rules that apply every time a value is checked:
type Database struct {
Driver string `validate:"oneof(sqlite,postgres)"`
MaxOpenConns int `validate:"min(1)"`
}
type CLIConfig struct {
Database *Database
}
binding, err := model.NewBinding[CLIConfig]()
if err != nil {
return err
}
if err := binding.Validate(ctx, &cfg); err != nil {
return err
}
Nested structs and nonnil pointers to structs are traversed automatically. A nil pointer is not allocated by Validate; use default:"dive" and ApplyDefaults when the nested object must exist.
Optional values and collections
type Endpoint struct {
URL string `validate:"min(1)"`
}
type Runner struct {
Alias string `validate:"omitempty,min(3)"`
Labels []string `validateElem:"min(2)"`
Endpoints []Endpoint `validateElem:"dive"`
}
omitempty skips the field's rules when its value is zero. validateElem runs rules on slice or array elements and map values. Use validateElem:"dive" by itself to traverse struct elements; nil pointer or nonstruct elements produce a dive validation issue. The current implementation does not run other element rules when dive is present.
Custom rules
See Built-in rules for the complete rule list and supported types.
Register application-specific rules during binding construction:
nonblank := model.NewRule[string]("nonblank", func(value string, _ ...string) error {
if strings.TrimSpace(value) == "" {
return errors.New("must contain non-whitespace text")
}
return nil
})
type Job struct {
Name string `validate:"nonblank"`
}
binding, err := model.NewBinding[Job](model.WithRules(nonblank))
A custom rule with the same name and exact field type overrides a built-in rule. Rule functions may run concurrently, so synchronize mutable state they capture.
Read validation failures
Constraint failures are collected in *validation.Error. Cancellation and operational errors return directly.
err := binding.Validate(ctx, &job)
var issues *validation.Error
if errors.As(err, &issues) {
for path, failures := range issues.ByField() {
for _, failure := range failures {
fmt.Printf("%s: %s: %v\n", path, failure.Rule, failure.Err)
}
}
}
Field paths use exported Go names such as Database.Driver and Endpoints[0].URL. For a conditional rule involving several fields, see Use cases.