Parsing
What is schema.Parse()?
To validate and parse your data into a destination pointer you can use the schema.Parse()
function. The function signature looks like this:
schema.Parse(data, &dest, options...)
This works with any Zog Schema:
// string
var dest string
z.String().Min(3).Parse("test", &dest)
// structs
var dest User
z.Struct(z.Schema{"name": z.String().Min(3)}).Parse(map[string]any{"name": "test"}, &dest)
Under the hood Zog follows the Parsing Execution Structure and does a bunch of things under the hood to make sure your data is parsed correctly. Such as checking for zero values, coercing types, etc...
Coercion
Zog will attempt to coerce the data into the correct type. For example if you have a z.Int()
schema and you pass in a "1"
it will be coerced into an int
type. This behaviour, like almost everything else in Zog, can be customized. Zog provides two main ways to customize coercion:
- Global Coercion - Change the default coercion behaviour for all schemas. More details on this in the configuration page.
- Per schema coercers - Define custom coercion functions for your schemas.
Per schema coercers
You can define custom coercion functions for your schemas by using the z.WithCoercer()
schema option.
z.String(z.WithCoercer(func(data any) (any, error) {
return "test", nil // now the result will be "test" no matter the input
})).Parse("abc", &dest) // dest will be "test"
Parsing Execution Structure
- Pretransforms
- On error all parsing and validation stops and ZogIssues are returned.
- Can be caught by catch
- Default Check -> Assigns default value if the value is nil value
- Optional Check -> Stops validation if the value is nil value
- Casting -> Attempts to cast the value to the correct type
- On error all parsing and validation stops and ZogIssues are returned
- Can be caught by catch
- Required check ->
- On error: aborts if the value is its nil value and returns a required ZogIssue.
- Can be caught by catch
- Tests -> Run all tests on the value (including required)
- On error: validation ZogIssues are added to the ZogIssueList or ZogIssueMap. All validation functions are run even if one of them fails.
- Can be caught by catch
- PostTransforms -> Run all postTransforms on the value.