MCPcopy
hub / github.com/danielgtaylor/huma / ExampleModelValidator

Function ExampleModelValidator

validate_test.go:1541–1567  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

1539}
1540
1541func ExampleModelValidator() {
1542 // Define a type you want to validate.
1543 type Model struct {
1544 Name string `json:"name" maxLength:"5"`
1545 Age int `json:"age" minimum:"25"`
1546 }
1547
1548 typ := reflect.TypeFor[Model]()
1549
1550 // Unmarshal some JSON into an `any` for validation. This input should not
1551 // validate against the schema for the struct above.
1552 var val any
1553 json.Unmarshal([]byte(`{"name": "abcdefg", "age": 1}`), &val)
1554
1555 // Validate the unmarshaled data against the type and print errors.
1556 validator := huma.NewModelValidator()
1557 errs := validator.Validate(typ, val)
1558 fmt.Println(errs)
1559
1560 // Try again with valid data!
1561 json.Unmarshal([]byte(`{"name": "foo", "age": 25}`), &val)
1562 errs = validator.Validate(typ, val)
1563 fmt.Println(errs)
1564
1565 // Output: [expected number >= 25 (age: 1) expected length <= 5 (name: abcdefg)]
1566 // []
1567}
1568
1569var BenchValidatePB *huma.PathBuffer
1570var BenchValidateRes *huma.ValidateResult

Callers

nothing calls this directly

Calls 2

ValidateMethod · 0.95
UnmarshalMethod · 0.65

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…