zog

package module
v0.0.0-...-d8dd4c4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 20, 2025 License: MIT Imports: 12 Imported by: 0

README

ZOG - A Zod & Yup like Schema Parser & Validator for GO

Coverage Status Go Report Card GitHub tag Go Reference

Mentioned in Awesome Go Mentioned in Awesome Templ stars - zog

view - Documentation

Zog is a schema builder for runtime value parsing and validation. Define a schema, transform a value to match, assert the shape of an existing value, or both. Zog schemas are extremely expressive and allow modeling complex, interdependent validations, or value transformations.

Killer Features:

  • Concise yet expressive schema interface, equipped to model simple to complex data models
  • Zod-like API, use method chaining to build schemas in a typesafe manner
  • Extensible: add your own Tests and Schemas
  • Rich errors with detailed context, make debugging a breeze
  • Fast: Zog is one of the fastest Go validation libraries. We are just behind the goplayground/validator for most of the govalidbench benchmarks.
  • Built-in coercion support for most types
  • Zero dependencies!
  • Four Helper Packages
    • zenv: parse environment variables
    • zhttp: parse http forms & query params
    • zjson: parse json
    • i18n: Opinionated solution to good i18n zog errors

API Stability:

  • I will consider the API stable when we reach v1.0.0
  • However, I believe very little API changes will happen from the current implementation. The APIs most likely to change are the data providers (please don't make your own if possible use the helpers whose APIs will not change meaningfully) and the z.Ctx most other APIs should remain the same. I could be wrong but I don't expect many breaking changes.
  • Although we want to keep breaking changes to a minimum, Zog is still in version 0 and will have breaking changes in the minor versions as per semver. So please be careful when upgrading minor versions.

Introduction

0. Read the docs at zog.dev

Or don't, below is the quickstart guide

1 Install
go get github.com/Oudwins/zog
2 Create a user schema and its struct
import (
	z "github.com/Oudwins/zog"
)

type User struct {
	Name string
	Age  int
}

var userSchema = z.Struct(z.Schema{
	// its very important that schema keys like "name" match the struct field name NOT the input data
	"name": z.String().Min(3, z.Message("Override default message")).Max(10),
	"age":  z.Int().GT(18),
})
3 Validate your schema

Using schema.Parse()

func main() {
	u := User{}
	m := map[string]string{
		"name": "Zog",
		"age":  "", // won't return an error because fields are optional by default
	}
	errsMap := userSchema.Parse(m, &u)
	if errsMap != nil {
		// handle errors -> see Errors section
	}
	u.Name // "Zog"
	// note that this might look weird but we didn't say age was required so Zog just skipped the empty string and we are left with the uninitialized int
	// If we need 0 to be a valid value for age we can use a pointer to an int which will be nil if the value was not present in the input data
	u.Age // 0
}

Using schema.Validate()

func main() {
	u := User{
		Name: "Zog",
		Age:  0, // wont return an error because fields are optional by default otherwise it will error
	}
	errsMap := userSchema.Validate(&u)
	if errsMap != nil {
		// handle errors -> see Errors section
	}
}
4. Its easy to use with http & json

The zhttp package has you covered for JSON, Forms and Query Params, just do:

import (
	zhttp "github.com/Oudwins/zog/zhttp"
)

err := userSchema.Parse(zhttp.Request(r), &user)

If you are receiving json some other way you can use the zjson package

import (
	zjson "github.com/Oudwins/zog/zjson"
)

err := userSchema.Parse(zjson.Decode(bytes.NewReader(jsonBytes)), &user)
5. Or to validate your environment variables

The zenv package has you covered, just do:

import (
	zenv "github.com/Oudwins/zog/zenv"
)

err := envSchema.Parse(zenv.NewDataProvider(), &envs)
6. You can also parse individual fields
var t = time.Time
errsList := Time().Required().Parse("2020-01-01T00:00:00Z", &t)
7 Transform Data without limits
var dest []string
schema := z.Preprocess(func(data any, ctx z.Ctx) ([]string, error) {
	s := data.(string) // don't do this, actually check the type
	return strings.Split(s, ","), nil
}, z.Slice(z.String().Trim().Email().Required()))
errs := schema.Parse("foo@bar.com,bar@foo.com", &dest) // dest = [foo@bar.com bar@foo.com]

Roadmap

These are some of the things I want to add to zog before v1.0.0

  • Support for schema.Clone()
  • support for catch & default for structs & slices
  • Struct generation from the schemas

Support

The damm domain costs me some outrageous amount like 100$ a year, so if any one wants to help cover that cost through github sponsors that is more than welcome.

Acknowledgments

  • Big thank you to @AlexanderArvidsson for being there to talk about architecture and design decisions. It helped a lot to have someone to bounce ideas off of
  • Credit for all the inspiration goes to /colinhacks/zod & /jquense/yup
  • Credit for the initial idea goes to anthony (@anthonyGG) -> /anthdm/superkit he made a hacky version of this idea that I used as a starting point, I was never happy with it so I inspired me to rewrite it from scratch. I owe him a lot
  • Credit for the zod logo goes to /colinhacks/zod

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Issues = issueHelpers{}

Functions

This section is empty.

Types

type BoolSchema

type BoolSchema[T ~bool] struct {
	// contains filtered or unexported fields
}

func Bool

func Bool(opts ...SchemaOption) *BoolSchema[bool]

Returns a new Bool Shape

func (*BoolSchema[T]) Catch

func (v *BoolSchema[T]) Catch(val T) *BoolSchema[T]

sets the catch value (i.e the value to use if the validation fails)

func (*BoolSchema[T]) Default

func (v *BoolSchema[T]) Default(val T) *BoolSchema[T]

sets the default value

func (*BoolSchema[T]) EQ

func (v *BoolSchema[T]) EQ(val T) *BoolSchema[T]

func (*BoolSchema[T]) False

func (v *BoolSchema[T]) False() *BoolSchema[T]

func (*BoolSchema[T]) Optional

func (v *BoolSchema[T]) Optional() *BoolSchema[T]

marks field as optional

func (*BoolSchema[T]) Parse

func (v *BoolSchema[T]) Parse(data any, dest *T, options ...ExecOption) ZogIssueList

Parse data into destination pointer

func (*BoolSchema[T]) Required

func (v *BoolSchema[T]) Required(options ...TestOption) *BoolSchema[T]

! MODIFIERS marks field as required

func (*BoolSchema[T]) Test

func (v *BoolSchema[T]) Test(t p.Test[*T]) *BoolSchema[T]

func (*BoolSchema[T]) TestFunc

func (v *BoolSchema[T]) TestFunc(testFunc p.BoolTFunc[*T], options ...p.TestOption) *BoolSchema[T]

Create a custom test function for the schema. This is similar to Zod's `.refine()` method.

func (*BoolSchema[T]) Transform

func (v *BoolSchema[T]) Transform(transform p.Transform[*T]) *BoolSchema[T]

Adds a transform function to the schema. Runs in the order it is called (i.e schema.True().Transform(...) will run the transform after the True test)

func (*BoolSchema[T]) True

func (v *BoolSchema[T]) True() *BoolSchema[T]

func (*BoolSchema[T]) Validate

func (v *BoolSchema[T]) Validate(val *T, options ...ExecOption) ZogIssueList

Validate data against schema

type BoolTFunc

type BoolTFunc[T any] p.BoolTFunc[T]

Function signature for bool tests. Takes the value and the context and returns a boolean. This is the function passed to the TestFunc method.

type CoercerFunc

type CoercerFunc = conf.CoercerFunc

type ComplexZogSchema

type ComplexZogSchema interface {
	ZogSchema
	Parse(val any, dest any, options ...ExecOption) ZogIssueMap
}

This is a common interface for all complex schemas (i.e structs, slices, pointers...) You can use this to pass any complex schema around

type Ctx

type Ctx = p.Ctx

This is the context that is passed through an entire execution of `schema.Parse()` or `schema.Validate()`. You can use it to pass a key/value for a specific execution. More about context in the [docs](https://zog.dev/context)

type Custom

type Custom[T any] struct {
	// contains filtered or unexported fields
}

func CustomFunc

func CustomFunc[T any](fn func(ptr *T, ctx Ctx) bool, opts ...TestOption) *Custom[T]

func (*Custom[T]) Parse

func (c *Custom[T]) Parse(data any, destPtr *T, options ...ExecOption) ZogIssueList

func (*Custom[T]) Validate

func (c *Custom[T]) Validate(dataPtr *T, options ...ExecOption) ZogIssueList

type ExecOption

type ExecOption = func(p *p.ExecCtx)

Options that can be passed to a `schema.Parse()` call

func WithCtxValue

func WithCtxValue(key string, val any) ExecOption

func WithErrFormatter deprecated

func WithErrFormatter(fmter IssueFmtFunc) ExecOption

Deprecated: use WithIssueFormatter instead Deprecated for naming consistency

func WithIssueFormatter

func WithIssueFormatter(fmter IssueFmtFunc) ExecOption

Sets the issue formatter for the execution context. This is used to format the issues messages during execution. This follows principle of most specific wins. So default formatter < execution formatter < test specific formatter (i.e MessageFunc)

type FileSchema

type FileSchema[T multipart.FileHeader] struct {
	// contains filtered or unexported fields
}

func File

Returns a new String Shape

func (*FileSchema[T]) Default

func (v *FileSchema[T]) Default(val T) *FileSchema[T]

sets the default value

func (*FileSchema[T]) Default2

func (v *FileSchema[T]) Default2(val T) *FileSchema[T]

sets the default value

func (*FileSchema[T]) Optional

func (v *FileSchema[T]) Optional() *FileSchema[T]

marks field as optional

func (*FileSchema[T]) Parse

func (v *FileSchema[T]) Parse(data any, dest *T, options ...ExecOption) ZogIssueList

parses the value and stores it in the destination

func (*FileSchema[T]) Required

func (v *FileSchema[T]) Required(options ...TestOption) *FileSchema[T]

marks field as required

func (*FileSchema[T]) Validate

func (v *FileSchema[T]) Validate(data *T, options ...ExecOption) ZogIssueList

Validates a number pointer

type IssueFmtFunc

type IssueFmtFunc = p.IssueFmtFunc

Function signature for issue formatters. Takes the issue and the context and returns the formatted issue.

type NotStringSchema

type NotStringSchema[T likeString] interface {
	OneOf(enum []T, options ...TestOption) *StringSchema[T]
	Len(n int, options ...TestOption) *StringSchema[T]
	Email(options ...TestOption) *StringSchema[T]
	URL(options ...TestOption) *StringSchema[T]
	HasPrefix(s T, options ...TestOption) *StringSchema[T]
	HasSuffix(s T, options ...TestOption) *StringSchema[T]
	Contains(sub T, options ...TestOption) *StringSchema[T]
	ContainsUpper(options ...TestOption) *StringSchema[T]
	ContainsDigit(options ...TestOption) *StringSchema[T]
	ContainsSpecial(options ...TestOption) *StringSchema[T]
	UUID(options ...TestOption) *StringSchema[T]
	Match(regex *regexp.Regexp, options ...TestOption) *StringSchema[T]
}

type NumberSchema

type NumberSchema[T Numeric] struct {
	// contains filtered or unexported fields
}

func Float deprecated

func Float(opts ...SchemaOption) *NumberSchema[float64]

Deprecated: Use Float64 instead creates a new float64 schema

func Float32

func Float32(opts ...SchemaOption) *NumberSchema[float32]

func Float64

func Float64(opts ...SchemaOption) *NumberSchema[float64]

func Int

func Int(opts ...SchemaOption) *NumberSchema[int]

creates a new int schema

func Int32

func Int32(opts ...SchemaOption) *NumberSchema[int32]

func Int64

func Int64(opts ...SchemaOption) *NumberSchema[int64]

func (*NumberSchema[T]) Catch

func (v *NumberSchema[T]) Catch(val T) *NumberSchema[T]

sets the catch value (i.e the value to use if the validation fails)

func (*NumberSchema[T]) Default

func (v *NumberSchema[T]) Default(val T) *NumberSchema[T]

sets the default value

func (*NumberSchema[T]) EQ

func (v *NumberSchema[T]) EQ(n T, options ...TestOption) *NumberSchema[T]

checks for equality

func (*NumberSchema[T]) GT

func (v *NumberSchema[T]) GT(n T, options ...TestOption) *NumberSchema[T]

checks for greater

func (*NumberSchema[T]) GTE

func (v *NumberSchema[T]) GTE(n T, options ...TestOption) *NumberSchema[T]

checks for greater or equal

func (*NumberSchema[T]) LT

func (v *NumberSchema[T]) LT(n T, options ...TestOption) *NumberSchema[T]

checks for lesser

func (*NumberSchema[T]) LTE

func (v *NumberSchema[T]) LTE(n T, options ...TestOption) *NumberSchema[T]

checks for lesser or equal

func (*NumberSchema[T]) OneOf

func (v *NumberSchema[T]) OneOf(enum []T, options ...TestOption) *NumberSchema[T]

Check that the value is one of the enum values

func (*NumberSchema[T]) Optional

func (v *NumberSchema[T]) Optional() *NumberSchema[T]

marks field as optional

func (*NumberSchema[T]) Parse

func (v *NumberSchema[T]) Parse(data any, dest *T, options ...ExecOption) ZogIssueList

parses the value and stores it in the destination

func (*NumberSchema[T]) Required

func (v *NumberSchema[T]) Required(options ...TestOption) *NumberSchema[T]

marks field as required

func (*NumberSchema[T]) Test

func (v *NumberSchema[T]) Test(t Test[*T]) *NumberSchema[T]

custom test function call it -> schema.Test(test, options)

func (*NumberSchema[T]) TestFunc

func (v *NumberSchema[T]) TestFunc(testFunc BoolTFunc[*T], options ...TestOption) *NumberSchema[T]

Create a custom test function for the schema. This is similar to Zod's `.refine()` method.

func (*NumberSchema[T]) Transform

func (v *NumberSchema[T]) Transform(transform p.Transform[*T]) *NumberSchema[T]

Adds a transform function to the schema. Runs in the order it is called

func (*NumberSchema[T]) Validate

func (v *NumberSchema[T]) Validate(data *T, options ...ExecOption) ZogIssueList

Validates a number pointer

type Numeric

type Numeric = constraints.Ordered

type ParsingOption deprecated

type ParsingOption = ExecOption

Deprecated: use ExecOption instead

type PointerSchema

type PointerSchema struct {
	// contains filtered or unexported fields
}

func Ptr

func Ptr(schema ZogSchema) *PointerSchema

Ptr creates a pointer ZogSchema

func (*PointerSchema) NotNil

func (v *PointerSchema) NotNil(options ...TestOption) *PointerSchema

func (*PointerSchema) Parse

func (v *PointerSchema) Parse(data any, dest any, options ...ExecOption) ZogIssueMap

Parse the data into the destination pointer

func (*PointerSchema) Validate

func (v *PointerSchema) Validate(data any, options ...ExecOption) ZogIssueMap

Validates a pointer pointer

type PreprocessSchema

type PreprocessSchema[F any, T any] struct {
	// contains filtered or unexported fields
}

func Preprocess

func Preprocess[F any, T any](fn func(data F, ctx Ctx) (out T, err error), schema ZogSchema) *PreprocessSchema[F, T]

out should never be a pointer type

func (*PreprocessSchema[F, T]) Parse

func (s *PreprocessSchema[F, T]) Parse(data F, destPtr *T, options ...ExecOption) ZogIssueList

func (*PreprocessSchema[F, T]) Validate

func (s *PreprocessSchema[F, T]) Validate(data *T, options ...ExecOption) ZogIssueList

type PrimitiveZogSchema

type PrimitiveZogSchema[T p.ZogPrimitive] interface {
	ZogSchema
	Parse(val any, dest *T, options ...ExecOption) ZogIssueList
}

This is a common interface for all primitive schemas (i.e strings, numbers, booleans, time.Time...) You can use this to pass any primitive schema around

type Schema

type Schema = Shape

deprecated: use z.Struct(z.Shape{}) instead A map of field names to zog schemas

type SchemaOption

type SchemaOption = func(s ZogSchema)

Options that can be passed to a `schema.New()` call

func WithCoercer

func WithCoercer(c conf.CoercerFunc) SchemaOption

type Shape

type Shape map[string]ZogSchema

A map of field names to zog schemas

type SliceSchema

type SliceSchema struct {
	// contains filtered or unexported fields
}

func Slice

func Slice(schema ZogSchema, opts ...SchemaOption) *SliceSchema

Creates a slice schema. That is a Zog representation of a slice. It takes a ZogSchema which will be used to validate against all the items in the slice.

func (*SliceSchema) Contains

func (v *SliceSchema) Contains(value any, options ...TestOption) *SliceSchema

Slice contains a specific value

func (*SliceSchema) Default

func (v *SliceSchema) Default(val any) *SliceSchema

sets the default value

func (*SliceSchema) Len

func (v *SliceSchema) Len(n int, options ...TestOption) *SliceSchema

Exact number of items

func (*SliceSchema) Max

func (v *SliceSchema) Max(n int, options ...TestOption) *SliceSchema

Maximum number of items

func (*SliceSchema) Min

func (v *SliceSchema) Min(n int, options ...TestOption) *SliceSchema

Minimum number of items

func (*SliceSchema) Optional

func (v *SliceSchema) Optional() *SliceSchema

marks field as optional

func (*SliceSchema) Parse

func (v *SliceSchema) Parse(data any, dest any, options ...ExecOption) ZogIssueMap

Only supports parsing from data=slice[any] to a dest =&slice[] (this can be typed. Doesn't have to be any)

func (*SliceSchema) Required

func (v *SliceSchema) Required(options ...TestOption) *SliceSchema

marks field as required

func (*SliceSchema) Test

func (v *SliceSchema) Test(t Test[any]) *SliceSchema

custom test function call it -> schema.Test(t z.Test)

func (*SliceSchema) TestFunc

func (v *SliceSchema) TestFunc(testFunc BoolTFunc[any], opts ...TestOption) *SliceSchema

Create a custom test function for the schema. This is similar to Zod's `.refine()` method.

func (*SliceSchema) Transform

func (v *SliceSchema) Transform(transform Transform[any]) *SliceSchema

Adds transform function to schema.

func (*SliceSchema) Validate

func (v *SliceSchema) Validate(data any, options ...ExecOption) ZogIssueMap

Validates a slice

type StringSchema

type StringSchema[T likeString] struct {
	// contains filtered or unexported fields
}

func String

func String(opts ...SchemaOption) *StringSchema[string]

Returns a new String Shape

func (*StringSchema[T]) Catch

func (v *StringSchema[T]) Catch(val T) *StringSchema[T]

sets the catch value (i.e the value to use if the validation fails)

func (*StringSchema[T]) Contains

func (v *StringSchema[T]) Contains(sub T, options ...TestOption) *StringSchema[T]

Test: checks that the value contains the substring

func (*StringSchema[T]) ContainsDigit

func (v *StringSchema[T]) ContainsDigit(options ...TestOption) *StringSchema[T]

Test: checks that the value contains a digit

func (*StringSchema[T]) ContainsSpecial

func (v *StringSchema[T]) ContainsSpecial(options ...TestOption) *StringSchema[T]

Test: checks that the value contains a special character

func (*StringSchema[T]) ContainsUpper

func (v *StringSchema[T]) ContainsUpper(options ...TestOption) *StringSchema[T]

Test: checks that the value contains an uppercase letter

func (*StringSchema[T]) Default

func (v *StringSchema[T]) Default(val T) *StringSchema[T]

sets the default value

func (*StringSchema[T]) Email

func (v *StringSchema[T]) Email(options ...TestOption) *StringSchema[T]

Test: checks that the value is a valid email address

func (*StringSchema[T]) HasPrefix

func (v *StringSchema[T]) HasPrefix(s T, options ...TestOption) *StringSchema[T]

Test: checks that the value has the prefix

func (*StringSchema[T]) HasSuffix

func (v *StringSchema[T]) HasSuffix(s T, options ...TestOption) *StringSchema[T]

Test: checks that the value has the suffix

func (*StringSchema[T]) Len

func (v *StringSchema[T]) Len(n int, options ...TestOption) *StringSchema[T]

Test: checks that the value is exactly n characters long

func (*StringSchema[T]) Match

func (v *StringSchema[T]) Match(regex *regexp.Regexp, options ...TestOption) *StringSchema[T]

Test: checks that value matches to regex

func (*StringSchema[T]) Max

func (v *StringSchema[T]) Max(n int, options ...TestOption) *StringSchema[T]

Test: checks that the value is at most n characters long

func (*StringSchema[T]) Min

func (v *StringSchema[T]) Min(n int, options ...TestOption) *StringSchema[T]

Test: checks that the value is at least n characters long

func (*StringSchema[T]) Not

func (v *StringSchema[T]) Not() NotStringSchema[T]

Not returns a schema that negates the next validation test. For example, `z.String().Not().Email()` validates that the string is NOT a valid email. Note: The negation only applies to the next validation test and is reset afterward.

func (*StringSchema[T]) OneOf

func (v *StringSchema[T]) OneOf(enum []T, options ...TestOption) *StringSchema[T]

Test: checks that the value is one of the enum values

func (*StringSchema[T]) Optional

func (v *StringSchema[T]) Optional() *StringSchema[T]

marks field as optional

func (*StringSchema[T]) Parse

func (v *StringSchema[T]) Parse(data any, dest *T, options ...ExecOption) ZogIssueList

Parses the data into the destination string. Returns a list of ZogIssues

func (*StringSchema[T]) Required

func (v *StringSchema[T]) Required(options ...TestOption) *StringSchema[T]

marks field as required

func (*StringSchema[T]) Test

func (v *StringSchema[T]) Test(t Test[*T]) *StringSchema[T]

! Tests custom test function call it -> schema.Test(t z.Test, opts ...TestOption)

func (*StringSchema[T]) TestFunc

func (v *StringSchema[T]) TestFunc(testFunc BoolTFunc[*T], options ...TestOption) *StringSchema[T]

Create a custom test function for the schema. This is similar to Zod's `.refine()` method.

func (*StringSchema[T]) Transform

func (v *StringSchema[T]) Transform(transform p.Transform[*T]) *StringSchema[T]

Adds a transform function to the schema. Runs in the order it is called

func (*StringSchema[T]) Trim

func (v *StringSchema[T]) Trim() *StringSchema[T]

Transform: trims the input data of whitespace if it is a string

func (*StringSchema[T]) URL

func (v *StringSchema[T]) URL(options ...TestOption) *StringSchema[T]

Test: checks that the value is a valid URL

func (*StringSchema[T]) UUID

func (v *StringSchema[T]) UUID(options ...TestOption) *StringSchema[T]

Test: checks that the value is a valid uuid

func (*StringSchema[T]) Validate

func (v *StringSchema[T]) Validate(data *T, options ...ExecOption) ZogIssueList

Validate Given string

type StructSchema

type StructSchema struct {
	// contains filtered or unexported fields
}

func Struct

func Struct(schema Shape) *StructSchema

Returns a new StructSchema which can be used to parse input data into a struct

func (*StructSchema) Extend

func (v *StructSchema) Extend(schema Shape) *StructSchema

Extend creates a new schema by adding additional fields from the provided schema. Fields in the provided schema override any existing fields with the same key.

Parameters:

  • schema: The schema containing fields to add

Returns a new schema with the additional fields

func (*StructSchema) Merge

func (v *StructSchema) Merge(other *StructSchema, others ...*StructSchema) *StructSchema

Merge combines two or more schemas into a new schema. It performs a shallow merge, meaning:

  • Fields with the same key from later schemas override earlier ones
  • PreTransforms, PostTransforms and tests are concatenated in order
  • Modifying nested schemas may affect the original schemas

Parameters:

  • other: The first schema to merge with
  • others: Additional schemas to merge

Returns a new schema containing the merged fields and transforms

func (*StructSchema) Omit

func (v *StructSchema) Omit(vals ...any) *StructSchema

Omit creates a new schema with specified fields removed. It accepts either strings or map[string]bool as arguments:

  • Strings directly specify fields to omit
  • For maps, fields are omitted when their boolean value is true

Returns a new schema with the specified fields removed

func (*StructSchema) Optional deprecated

func (v *StructSchema) Optional() *StructSchema

Deprecated: structs are not required or optional. They pass through to the fields. If you want to say that an entire struct may not exist you should use z.Ptr(z.Struct(...)) marks field as optional

func (*StructSchema) Parse

func (v *StructSchema) Parse(data any, destPtr any, options ...ExecOption) ZogIssueMap

Parses val into destPtr and validates each field based on the schema. Only supports val = map[string]any & dest = &struct

func (*StructSchema) Pick

func (v *StructSchema) Pick(picks ...any) *StructSchema

Pick creates a new schema keeping only the specified fields. It accepts either strings or map[string]bool as arguments:

  • Strings directly specify fields to keep
  • For maps, fields are kept when their boolean value is true

Returns a new schema containing only the specified fields

func (*StructSchema) Required deprecated

func (v *StructSchema) Required(options ...TestOption) *StructSchema

Deprecated: structs are not required or optional. They pass through to the fields. If you want to say that an entire struct may not exist you should use z.Ptr(z.Struct(...)) This now is a noop. But I believe most people expect it to work how it does now. marks field as required

func (*StructSchema) Test

func (v *StructSchema) Test(t Test[any]) *StructSchema

! VALIDATORS custom test function call it -> schema.Test(t z.Test)

func (*StructSchema) TestFunc

func (v *StructSchema) TestFunc(testFunc BoolTFunc[any], options ...TestOption) *StructSchema

Create a custom test function for the schema. This is similar to Zod's `.refine()` method.

func (*StructSchema) Transform

func (v *StructSchema) Transform(transform p.Transform[any]) *StructSchema

Adds posttransform function to schema

func (*StructSchema) Validate

func (v *StructSchema) Validate(dataPtr any, options ...ExecOption) ZogIssueMap

Validate a struct pointer given the struct schema. Usage: userSchema.Validate(&User, ...options)

type TFunc

type TFunc[T any] p.TFunc[T]

Function signature for tests. Takes the value and the context and returns a boolean. This used to be a function you could pass to the schema.Test method -> `s.Test(z.TFunc(fn))`. But that has been deprecated. Use `schema.TFunc(fn)` instead.

type Test

type Test[T any] p.Test[T]

Test is the test object. It is the struct that represents an individual validation. For example `z.String().Min(3)` is a test that checks if the string is at least 3 characters long.

func TestFunc

func TestFunc[T any](IssueCode zconst.ZogIssueCode, fn BoolTFunc[T], options ...p.TestOption) Test[T]

Creates a reusable testFunc you can add to schemas by doing schema.Test(z.TestFunc()). Has the same API as schema.TestFunc() so it is recommended you use that one for non reusable tests.

type TestOption

type TestOption = p.TestOption

Options that can be passed to a test

func IssueCode

func IssueCode(code zconst.ZogIssueCode) TestOption

IssueCode is a function that allows you to set a custom issue code for the test. Most useful for TestFuncs:

z.String().TestFunc(..., z.IssueCode("just_provide_a_string" or use values in zconst))

func IssuePath

func IssuePath(path string) TestOption

IssuePath is a function that allows you to set a custom issue path for the test. Beware with using this as it is not typesafe and can lead to unexpected behavior if you change the schema or have a typo. Usage:

z.Struct(

z.Shape {
    "Name": z.String().Required(z.IssuePath("fullname")),
	"Fullname": z.String(),
}

)

func Message

func Message(msg string) TestOption

Message is a function that allows you to set a custom message for the test.

func MessageFunc

func MessageFunc(fn p.IssueFmtFunc) TestOption

MessageFunc is a function that allows you to set a custom message formatter for the test.

func Params

func Params(params map[string]any) TestOption

Params is a function that allows you to set a custom params for the test. You may then access these values when formatting test errors in the IssueFmtFunc

type TimeFunc

type TimeFunc func(opts ...SchemaOption) *TimeSchema
var Time TimeFunc = func(opts ...SchemaOption) *TimeSchema {
	t := &TimeSchema{
		coercer: conf.Coercers.Time,
	}
	for _, opt := range opts {
		opt(t)
	}
	return t
}

Returns a new Time Shape

func (TimeFunc) Format

func (t TimeFunc) Format(format string) SchemaOption

WARNING ONLY SUPPOORTS Shape.Parse! Sets the string format for the time schema Usage is: z.Time(z.Time.Format(time.RFC3339))

func (TimeFunc) FormatFunc

func (t TimeFunc) FormatFunc(format func(data string) (time.Time, error)) SchemaOption

WARNING ONLY SUPPOORTS Shape.Parse! Sets the format function for the time schema. Usage is:

z.Time(z.Time.FormatFunc(func(data string) (time.Time, error) {
	return time.Parse(time.RFC3339, data)
}))

type TimeSchema

type TimeSchema struct {
	// contains filtered or unexported fields
}

func (*TimeSchema) After

func (v *TimeSchema) After(t time.Time, opts ...TestOption) *TimeSchema

Checks that the value is after the given time

func (*TimeSchema) Before

func (v *TimeSchema) Before(t time.Time, opts ...TestOption) *TimeSchema

Checks that the value is before the given time

func (*TimeSchema) Catch

func (v *TimeSchema) Catch(val time.Time) *TimeSchema

sets the catch value (i.e the value to use if the validation fails)

func (*TimeSchema) Default

func (v *TimeSchema) Default(val time.Time) *TimeSchema

sets the default value

func (*TimeSchema) EQ

func (v *TimeSchema) EQ(t time.Time, opts ...TestOption) *TimeSchema

Checks that the value is equal to the given time

func (*TimeSchema) Optional

func (v *TimeSchema) Optional() *TimeSchema

marks field as optional

func (*TimeSchema) Parse

func (v *TimeSchema) Parse(data any, dest *time.Time, options ...ExecOption) ZogIssueList

Parses the data into the destination time.Time. Returns a list of errors

func (*TimeSchema) Required

func (v *TimeSchema) Required(options ...TestOption) *TimeSchema

marks field as required

func (*TimeSchema) Test

func (v *TimeSchema) Test(t Test[*time.Time]) *TimeSchema

custom test function call it -> schema.Test(z.Test{Func: func (val *time.Time, ctx z.Ctx) { my test }})

func (*TimeSchema) TestFunc

func (v *TimeSchema) TestFunc(testFunc BoolTFunc[*time.Time], options ...TestOption) *TimeSchema

Create a custom test function for the schema. This is similar to Zod's `.refine()` method.

func (*TimeSchema) Transform

func (v *TimeSchema) Transform(transform Transform[*time.Time]) *TimeSchema

Adds posttransform function to schema

func (*TimeSchema) Validate

func (v *TimeSchema) Validate(data *time.Time, options ...ExecOption) ZogIssueList

Validates an existing time.Time

type Transform

type Transform[T any] p.Transform[T]

Function signature for transforms. Takes the value pointer and the context and returns an optional error.

type ZogIssue

type ZogIssue = p.ZogIssue

This is a type for the ZogIssue type. It is the type of all the errors returned from zog.

type ZogIssueList

type ZogIssueList = p.ZogIssueList

This is a type for the ZogErrList type. It is a list of ZogIssues returned from parsing primitive schemas. The type is []ZogIssue

type ZogIssueMap

type ZogIssueMap = p.ZogIssueMap

This is a type for the ZogIssueMap type. It is a map[string][]ZogIssue returned from parsing complex schemas. The type is map[string][]ZogIssue All errors are returned in a flat map, not matter how deep the schema is. For example:

schema := z.Struct(z.Shape{
  "address": z.Struct(z.Shape{
    "street": z.String().Min(3).Max(10),
    "city": z.String().Min(3).Max(10),
  }),
  "fields": z.Slice(z.String().Min(3).Max(10)),
})
errors = map[string][]ZogIssue{
  "address.street": []ZogIssue{....}, // error for the street field in the address struct
  "fields[0]": []ZogIssue{...}, // error for the first field in the slice
}

type ZogSchema

type ZogSchema interface {
	// contains filtered or unexported methods
}

The ZogSchema is the interface all schemas must implement This is most useful for internal use. If you are looking to pass schemas around, use the ComplexZogSchema or PrimitiveZogSchema interfaces if possible.

Directories

Path Synopsis
en
es
parsers

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL