Help us shape the future of Go! Take the 2026 Go Developer Survey

z

package
v0.26.0 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Overview

Package z parses untrusted input into typed Go values with Zod-inspired schemas, and checks outgoing values against the same contracts.

var Login = z.Struct[LoginInput](z.Shape{
	"email":    z.String().Trim().Email(),
	"password": z.String().Min(12),
})

in, err := Login.Parse(map[string]any{"email": "a@b.co", "password": "..."})

Schemas are immutable values: every modifier returns a new schema, so a schema can be shared by any number of goroutines.

Parse returns every problem at once as Issues (see AsIssues), which web.Parse turns into a 422 response. Builders cover strings, numbers, booleans, times, enums, files, slices, maps and Struct (or FromTags from `validate` tags); JSONSchema exports a schema for the OpenAPI document.

See https://github.com/AlexGalhardo/vukem/blob/main/docs/validation.md.

Example
package main

import (
	"fmt"

	"github.com/AlexGalhardo/vukem/z"
)

type registerInput struct {
	Email    string `json:"email"`
	Password string `json:"password"`
	Age      int    `json:"age"`
}

var registerSchema = z.Struct[registerInput](z.Shape{
	"email":    z.String().Trim().Email(),
	"password": z.String().Min(12),
	"age":      z.Int().Min(18),
})

func main() {
	in, err := registerSchema.Parse(map[string]any{
		"email":    "  ada@example.com ",
		"password": "correct horse battery",
		"age":      36,
	})
	fmt.Printf("%q %d %v\n", in.Email, in.Age, err)
}
Output:
"ada@example.com" 36 <nil>

Index

Examples

Constants

View Source
const (
	CodeRequired         = "required"
	CodeInvalidType      = "invalid_type"
	CodeTooSmall         = "too_small"
	CodeTooBig           = "too_big"
	CodeInvalidString    = "invalid_string"
	CodeInvalidEnum      = "invalid_enum"
	CodeUnrecognizedKeys = "unrecognized_keys"
	CodeNotMultiple      = "not_multiple_of"
	CodeInvalidDate      = "invalid_date"
	CodeNotUnique        = "not_unique"
	CodeCustom           = "custom"
)

Issue codes.

View Source
const CodeInvalidFile = "invalid_file"

CodeInvalidFile reports a file whose type or extension is not allowed.

Variables

This section is empty.

Functions

func FieldError

func FieldError(path, message string) error

FieldError returns an error for Refine callbacks that points at a field path relative to the refined value. Its message is never translated; use FieldErrorKey for a translatable one.

func FieldErrorKey added in v0.24.0

func FieldErrorKey(path, key, fallback string, params map[string]any) error

FieldErrorKey returns a translatable error for Refine callbacks (and Custom parsers). The issue points at path relative to the refined value ("" for the value itself), gets Code CodeCustom, Key key and Params params, and its Message is fallback with {field} and params filled in. Issues.Localize rebuilds the message from the template for key, so with package i18n a key "confirmed" is looked up as "validation.confirmed".

func JSONSchema added in v0.15.0

func JSONSchema(s AnySchema) map[string]any

JSONSchema returns the JSON Schema (2020-12) of s: types, required keys, lengths, ranges, formats, patterns, enums, defaults and descriptions. Refine, Transform and Custom logic cannot be expressed and is omitted, so the server may reject values the schema allows, never the reverse.

func ParseJSON

func ParseJSON[T any](r io.Reader, s Schema[T]) (T, error)

ParseJSON decodes JSON from r and parses it with s.

Types

type AnySchema

type AnySchema interface {
	// GoType is the Go type the schema produces.
	GoType() reflect.Type
	// contains filtered or unexported methods
}

AnySchema is implemented by every schema in this package. Composite schemas (Slice, Map, Shape fields) accept any schema through it.

type BoolSchema

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

BoolSchema parses booleans. From forms it accepts true/false, 1/0, on/off and yes/no (an unchecked checkbox is absent, so use Default(false)).

func Bool

func Bool() BoolSchema

Bool returns a schema for bool.

func (BoolSchema) Check

func (s BoolSchema) Check(v bool) error

Check implements Schema.

func (BoolSchema) Default

func (s BoolSchema) Default(v bool) BoolSchema

Default uses v when the key is absent.

func (BoolSchema) Describe

func (s BoolSchema) Describe(text string) BoolSchema

Describe sets a description used by schema exports.

func (BoolSchema) GoType

func (BoolSchema) GoType() reflect.Type

GoType implements AnySchema.

func (BoolSchema) Message

func (s BoolSchema) Message(code, message string) BoolSchema

Message overrides the message for an issue code.

func (BoolSchema) Nullable

func (s BoolSchema) Nullable() BoolSchema

Nullable allows null.

func (BoolSchema) Optional

func (s BoolSchema) Optional() BoolSchema

Optional allows the key to be absent.

func (BoolSchema) Parse

func (s BoolSchema) Parse(in any) (bool, error)

Parse implements Schema.

func (BoolSchema) Refine

func (s BoolSchema) Refine(fn func(bool) error) BoolSchema

Refine adds a custom check.

type CustomSchema

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

CustomSchema parses with a user function.

func Custom

func Custom[T any](fn func(in any) (T, error)) CustomSchema[T]

Custom returns a schema whose parsing is done by fn; a returned error becomes an issue with its message (FieldError and FieldErrorKey are honored as in Refine).

func (CustomSchema[T]) Check

func (s CustomSchema[T]) Check(v T) error

Check implements Schema.

func (CustomSchema[T]) GoType

func (CustomSchema[T]) GoType() reflect.Type

GoType implements AnySchema.

func (CustomSchema[T]) Optional

func (s CustomSchema[T]) Optional() CustomSchema[T]

Optional allows the key to be absent.

func (CustomSchema[T]) Parse

func (s CustomSchema[T]) Parse(in any) (T, error)

Parse implements Schema.

type EnumSchema

type EnumSchema[T ~string] struct {
	// contains filtered or unexported fields
}

EnumSchema parses one of a fixed set of string values into T.

func Enum

func Enum(values ...string) EnumSchema[string]

Enum returns a schema accepting one of values; it panics when values is empty.

func EnumOf

func EnumOf[T ~string](values ...T) EnumSchema[T]

EnumOf returns an enum schema for a named string type:

type Status string
z.EnumOf(StatusDraft, StatusPublished)

It panics when values is empty.

func (EnumSchema[T]) Check

func (s EnumSchema[T]) Check(v T) error

Check implements Schema.

func (EnumSchema[T]) Default

func (s EnumSchema[T]) Default(v T) EnumSchema[T]

Default uses v when the key is absent.

func (EnumSchema[T]) Describe

func (s EnumSchema[T]) Describe(text string) EnumSchema[T]

Describe sets a description used by schema exports.

func (EnumSchema[T]) GoType

func (EnumSchema[T]) GoType() reflect.Type

GoType implements AnySchema.

func (EnumSchema[T]) Message

func (s EnumSchema[T]) Message(code, message string) EnumSchema[T]

Message overrides the message for an issue code.

func (EnumSchema[T]) Nullable

func (s EnumSchema[T]) Nullable() EnumSchema[T]

Nullable allows null.

func (EnumSchema[T]) Optional

func (s EnumSchema[T]) Optional() EnumSchema[T]

Optional allows the key to be absent.

func (EnumSchema[T]) Parse

func (s EnumSchema[T]) Parse(in any) (T, error)

Parse implements Schema.

func (EnumSchema[T]) Refine

func (s EnumSchema[T]) Refine(fn func(T) error) EnumSchema[T]

Refine adds a custom check.

func (EnumSchema[T]) Values

func (s EnumSchema[T]) Values() []T

Values returns the allowed values.

type FileSchema added in v0.19.0

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

FileSchema validates uploaded files (*multipart.FileHeader, as put in web.Ctx.Input by multipart forms). The type is detected from the first 512 bytes of the content, never taken from the client.

"avatar": z.File().MaxSize(2 << 20).Types("image/png", "image/jpeg")

func File added in v0.19.0

func File() FileSchema

File returns a schema for an uploaded file.

func (FileSchema) Check added in v0.19.0

func (s FileSchema) Check(fh *multipart.FileHeader) error

Check implements Schema. Files are not JSON values, so it runs the rules on fh directly.

func (FileSchema) Describe added in v0.19.0

func (s FileSchema) Describe(text string) FileSchema

Describe sets a description used by schema exports.

func (FileSchema) Extensions added in v0.19.0

func (s FileSchema) Extensions(exts ...string) FileSchema

Extensions allows only these file name extensions (".png" or "png").

func (FileSchema) GoType added in v0.19.0

func (FileSchema) GoType() reflect.Type

GoType implements AnySchema.

func (FileSchema) MaxSize added in v0.19.0

func (s FileSchema) MaxSize(n int64) FileSchema

MaxSize rejects files larger than n bytes.

func (FileSchema) Message added in v0.19.0

func (s FileSchema) Message(code, message string) FileSchema

Message overrides the message for an issue code or key ("file.type").

func (FileSchema) Optional added in v0.19.0

func (s FileSchema) Optional() FileSchema

Optional allows the file to be absent.

func (FileSchema) Parse added in v0.19.0

func (s FileSchema) Parse(in any) (*multipart.FileHeader, error)

Parse implements Schema.

func (FileSchema) Refine added in v0.19.0

func (s FileSchema) Refine(fn func(*multipart.FileHeader) error) FileSchema

Refine adds a custom check.

func (FileSchema) Types added in v0.19.0

func (s FileSchema) Types(mimeTypes ...string) FileSchema

Types allows only these MIME types, detected from the content ("image/png", "application/pdf", "text/plain").

type Issue

type Issue struct {
	// Path is the dotted path to the value: "author.email", "tags.2".
	Path string `json:"path"`
	// Code is a stable machine-readable code (see Code* constants).
	Code string `json:"code"`
	// Message is a human-readable message.
	Message string `json:"message"`
	// Key is the message key Message was built from ("required",
	// "too_small.string", "string.email"...), or the key given to
	// FieldErrorKey, or "invalid" for a Refine or Custom error that is not a
	// FieldError; empty for other custom messages (Message overrides,
	// FieldError). Localize uses it.
	Key string `json:"-"`
	// Params holds the values used by the message, e.g. {"min": 3}.
	Params map[string]any `json:"params,omitempty"`
	// Err is the error a Refine callback or Custom parser returned when it
	// was not a FieldError: its text may be internal (a database error), so
	// Message is the generic "invalid" message and Err is for server logs
	// only. Return FieldError or FieldErrorKey for a client-facing message.
	Err error `json:"-"`
}

Issue is one problem found while parsing.

type Issues

type Issues []Issue //nolint:errname // mirrors Zod; reads naturally as a list of issues

Issues is the error returned by Parse. It lists every issue found, not only the first.

func AsIssues

func AsIssues(err error) (Issues, bool)

AsIssues extracts Issues from err. An error from FieldError or FieldErrorKey yields its single issue.

Example
package main

import (
	"fmt"

	"github.com/AlexGalhardo/vukem/z"
)

type registerInput struct {
	Email    string `json:"email"`
	Password string `json:"password"`
	Age      int    `json:"age"`
}

var registerSchema = z.Struct[registerInput](z.Shape{
	"email":    z.String().Trim().Email(),
	"password": z.String().Min(12),
	"age":      z.Int().Min(18),
})

func main() {
	_, err := registerSchema.Parse(map[string]any{"email": "nope", "password": "short", "age": 12})

	issues, _ := z.AsIssues(err)
	for _, field := range []string{"email", "password", "age"} {
		fmt.Printf("%s: %s\n", field, issues.First(field))
	}
}
Output:
email: The email field must be a valid email address.
password: The password field must be at least 12 characters.
age: The age field must be at least 18.

func (Issues) Error

func (is Issues) Error() string

Error implements error.

func (Issues) Fields

func (is Issues) Fields() map[string][]string

Fields groups messages by path, the shape used by validation responses.

func (Issues) First

func (is Issues) First(path string) string

First returns the first message for path, or "".

func (Issues) HTTPStatus added in v0.25.0

func (is Issues) HTTPStatus() int

HTTPStatus reports 422, so errs.Status and the web error handler treat Issues returned from a handler as a validation error.

func (Issues) Localize added in v0.18.0

func (is Issues) Localize(lookup func(key string) (string, bool)) Issues

Localize returns a copy of is with each built-in message rebuilt from the template lookup returns for the issue's Key, then its Code (for example a catalog's "validation.too_small.string" and "validation.too_small"). {field} becomes lookup("attributes.<name>") when present, where name is the last path segment ("first_name"), or the humanized name otherwise. Issues without a template, and custom messages without a key, are kept unchanged.

type MapSchema

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

MapSchema parses objects into map[string]V.

func Map

func Map(value AnySchema) MapSchema

Map returns a schema for an object with string keys and values matching value.

func (MapSchema) GoType

func (s MapSchema) GoType() reflect.Type

GoType implements AnySchema.

func (MapSchema) Max

func (s MapSchema) Max(n int) MapSchema

Max allows at most n keys.

func (MapSchema) Min

func (s MapSchema) Min(n int) MapSchema

Min requires at least n keys.

func (MapSchema) Nullable

func (s MapSchema) Nullable() MapSchema

Nullable allows null.

func (MapSchema) Optional

func (s MapSchema) Optional() MapSchema

Optional allows the key to be absent.

func (MapSchema) Parse

func (s MapSchema) Parse(in any) (any, error)

Parse returns the parsed map as any (map[string]V).

type Number

type Number interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64 |
		~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 |
		~float32 | ~float64
}

Number is the set of numeric types NumberSchema produces.

type NumberSchema

type NumberSchema[N Number] struct {
	// contains filtered or unexported fields
}

NumberSchema parses numbers of type N. It accepts JSON numbers and, from forms and query strings, numeric strings. Integer schemas reject fractions and out-of-range values; float schemas reject NaN and ±Inf.

func Float

func Float() NumberSchema[float64]

Float returns a schema for float64.

func Float32

func Float32() NumberSchema[float32]

Float32 returns a schema for float32.

func Int

func Int() NumberSchema[int]

Int returns a schema for int.

func Int32

func Int32() NumberSchema[int32]

Int32 returns a schema for int32.

func Int64

func Int64() NumberSchema[int64]

Int64 returns a schema for int64.

func NumberOf

func NumberOf[N Number]() NumberSchema[N]

NumberOf returns a schema for any numeric type, e.g. a named type.

func Uint

func Uint() NumberSchema[uint]

Uint returns a schema for uint.

func Uint64

func Uint64() NumberSchema[uint64]

Uint64 returns a schema for uint64.

func (NumberSchema[N]) Check

func (s NumberSchema[N]) Check(v N) error

Check implements Schema.

func (NumberSchema[N]) Default

func (s NumberSchema[N]) Default(v N) NumberSchema[N]

Default uses v when the key is absent.

func (NumberSchema[N]) Describe

func (s NumberSchema[N]) Describe(text string) NumberSchema[N]

Describe sets a description used by schema exports.

func (NumberSchema[N]) GoType

func (NumberSchema[N]) GoType() reflect.Type

GoType implements AnySchema.

func (NumberSchema[N]) Max

func (s NumberSchema[N]) Max(n N) NumberSchema[N]

Max requires v <= n.

func (NumberSchema[N]) Message

func (s NumberSchema[N]) Message(code, message string) NumberSchema[N]

Message overrides the message for an issue code or detailed key.

func (NumberSchema[N]) Min

func (s NumberSchema[N]) Min(n N) NumberSchema[N]

Min requires v >= n.

func (NumberSchema[N]) MultipleOf

func (s NumberSchema[N]) MultipleOf(m N) NumberSchema[N]

MultipleOf requires v to be a multiple of m.

func (NumberSchema[N]) NonNegative

func (s NumberSchema[N]) NonNegative() NumberSchema[N]

NonNegative requires v >= 0.

func (NumberSchema[N]) Nullable

func (s NumberSchema[N]) Nullable() NumberSchema[N]

Nullable allows null.

func (NumberSchema[N]) Optional

func (s NumberSchema[N]) Optional() NumberSchema[N]

Optional allows the key to be absent (the zero value is used). An empty string from a form counts as absent.

func (NumberSchema[N]) Parse

func (s NumberSchema[N]) Parse(in any) (N, error)

Parse implements Schema.

func (NumberSchema[N]) Positive

func (s NumberSchema[N]) Positive() NumberSchema[N]

Positive requires v > 0.

func (NumberSchema[N]) Refine

func (s NumberSchema[N]) Refine(fn func(N) error) NumberSchema[N]

Refine adds a custom check.

func (NumberSchema[N]) Transform

func (s NumberSchema[N]) Transform(fn func(N) N) NumberSchema[N]

Transform maps the parsed value.

type Schema

type Schema[T any] interface {
	AnySchema
	// Parse converts untrusted input (decoded JSON, form maps, strings)
	// into T. The error is an Issues value listing every problem.
	Parse(in any) (T, error)
	// Check validates an already typed value, e.g. data about to be sent
	// in a response. It uses the same rules as Parse.
	Check(v T) error
}

Schema is a schema that produces values of type T.

type Shape

type Shape map[string]AnySchema

Shape maps input keys to field schemas.

type SliceSchema

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

SliceSchema parses arrays into []E where E is the element schema's type. From forms, a single value is accepted as a one-element list.

func Slice

func Slice(elem AnySchema) SliceSchema

Slice returns a schema for a list whose elements match elem.

func (SliceSchema) Default

func (s SliceSchema) Default(v any) SliceSchema

Default uses v (a slice of the element type) when the key is absent. It panics when v has another type.

func (SliceSchema) Describe

func (s SliceSchema) Describe(text string) SliceSchema

Describe sets a description used by schema exports.

func (SliceSchema) GoType

func (s SliceSchema) GoType() reflect.Type

GoType implements AnySchema.

func (SliceSchema) Len

func (s SliceSchema) Len(n int) SliceSchema

Len requires exactly n items.

func (SliceSchema) Max

func (s SliceSchema) Max(n int) SliceSchema

Max allows at most n items.

func (SliceSchema) Message

func (s SliceSchema) Message(code, message string) SliceSchema

Message overrides the message for an issue code.

func (SliceSchema) Min

func (s SliceSchema) Min(n int) SliceSchema

Min requires at least n items.

func (SliceSchema) NonEmpty

func (s SliceSchema) NonEmpty() SliceSchema

NonEmpty is Min(1).

func (SliceSchema) Nullable

func (s SliceSchema) Nullable() SliceSchema

Nullable allows null.

func (SliceSchema) Optional

func (s SliceSchema) Optional() SliceSchema

Optional allows the key to be absent (nil slice).

func (SliceSchema) Parse

func (s SliceSchema) Parse(in any) (any, error)

Parse returns the parsed slice as any ([]E).

func (SliceSchema) Unique

func (s SliceSchema) Unique() SliceSchema

Unique rejects duplicate items.

type StringSchema

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

StringSchema parses strings. It rejects invalid UTF-8 and control characters other than tab, newline and carriage return (A05).

func String

func String() StringSchema

String returns a schema for string values. The empty string is a valid string; use Min(1) (or the "required" tag) to reject it.

func (StringSchema) Alpha

func (s StringSchema) Alpha() StringSchema

Alpha requires letters only.

func (StringSchema) Alphanum

func (s StringSchema) Alphanum() StringSchema

Alphanum requires letters and digits only.

func (StringSchema) Check

func (s StringSchema) Check(v string) error

Check implements Schema.

func (StringSchema) Default

func (s StringSchema) Default(v string) StringSchema

Default uses v when the key is absent.

func (StringSchema) Describe

func (s StringSchema) Describe(text string) StringSchema

Describe sets a description used by schema exports.

func (StringSchema) Email

func (s StringSchema) Email() StringSchema

Email requires an email address (addr-spec, no display name).

func (StringSchema) EndsWith

func (s StringSchema) EndsWith(suffix string) StringSchema

EndsWith requires suffix.

func (StringSchema) GoType

func (StringSchema) GoType() reflect.Type

GoType implements AnySchema.

func (StringSchema) Includes

func (s StringSchema) Includes(substring string) StringSchema

Includes requires substring.

func (StringSchema) Len

func (s StringSchema) Len(n int) StringSchema

Len requires exactly n characters (runes).

func (StringSchema) Max

func (s StringSchema) Max(n int) StringSchema

Max allows at most n characters (runes).

func (StringSchema) Message

func (s StringSchema) Message(code, message string) StringSchema

Message overrides the message for an issue code (or a detailed key such as "too_small.string"). Placeholders: {field}, {min}, {max}, ...

func (StringSchema) Min

func (s StringSchema) Min(n int) StringSchema

Min requires at least n characters (runes).

func (StringSchema) NonEmpty

func (s StringSchema) NonEmpty() StringSchema

NonEmpty is Min(1).

func (StringSchema) Nullable

func (s StringSchema) Nullable() StringSchema

Nullable allows null.

func (StringSchema) Numeric

func (s StringSchema) Numeric() StringSchema

Numeric requires a decimal number written as a string.

func (StringSchema) OneOf

func (s StringSchema) OneOf(values ...string) StringSchema

OneOf requires one of values (see also Enum).

func (StringSchema) Optional

func (s StringSchema) Optional() StringSchema

Optional allows the key to be absent (the zero value is used).

func (StringSchema) Parse

func (s StringSchema) Parse(in any) (string, error)

Parse implements Schema.

func (StringSchema) Preprocess added in v0.24.0

func (s StringSchema) Preprocess(fn func(string) string) StringSchema

Preprocess normalizes the value with fn before checks, e.g. stripping a phone number down to digits so Regex sees the normalized form. Pre-steps (Trim, ToLower, ToUpper, Preprocess) run in declaration order after the UTF-8 check and before every check (Min, Regex, Email...); Transform runs after the checks, and Refine last. The result is checked again for invalid UTF-8 and control characters (fail closed). The normalized value is what JSON Schema keywords (pattern, minLength...) describe. Preprocess panics if fn is nil.

func (StringSchema) Refine

func (s StringSchema) Refine(fn func(string) error) StringSchema

Refine adds a custom check; return FieldError for nested paths or FieldErrorKey for a translatable message.

func (StringSchema) Regex

func (s StringSchema) Regex(re *regexp.Regexp) StringSchema

Regex requires a match of re.

func (StringSchema) StartsWith

func (s StringSchema) StartsWith(prefix string) StringSchema

StartsWith requires prefix.

func (StringSchema) ToLower

func (s StringSchema) ToLower() StringSchema

ToLower lower-cases the value before checks.

func (StringSchema) ToUpper

func (s StringSchema) ToUpper() StringSchema

ToUpper upper-cases the value before checks.

func (StringSchema) Transform

func (s StringSchema) Transform(fn func(string) string) StringSchema

Transform maps the value after the checks; Refine sees the result. Use Preprocess to normalize before the checks.

func (StringSchema) Trim

func (s StringSchema) Trim() StringSchema

Trim removes leading and trailing white space before checks.

func (StringSchema) ULID

func (s StringSchema) ULID() StringSchema

ULID requires a ULID.

func (StringSchema) URL

func (s StringSchema) URL() StringSchema

URL requires an absolute http or https URL.

func (StringSchema) UUID

func (s StringSchema) UUID() StringSchema

UUID requires a UUID in canonical form.

type StructSchema

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

StructSchema parses objects into T.

func For

func For[T any]() StructSchema[T]

For returns the tag-derived schema for T, built once and cached. It panics like FromTags.

func FromTags

func FromTags[T any]() StructSchema[T]

FromTags builds a schema for T from `validate` struct tags, e.g.

type Login struct {
	Email    string `json:"email"    validate:"required,email"`
	Password string `json:"password" validate:"required,min=12"`
}

Rules: required, min=N, max=N, len=N, email, url, uuid, ulid, alpha, alphanum, numeric, oneof=a b c, regex=PATTERN (last rule), startswith=, endswith=, contains=, positive, unique, dive (rules after it apply to slice elements). Fields without "required" are optional; "required" on a string means non-empty, on a list present and not null (use min=1 for a non-empty list); pointers are optional and nullable; nested structs are parsed recursively. It panics on unknown rules or bad arguments, so mistakes surface at boot.

func Struct

func Struct[T any](shape Shape) StructSchema[T]

Struct returns a schema producing T from an object whose keys are described by shape. Keys map to fields by json, form or query tag, or by field name. It panics when a key has no field or the schema's type does not fit the field, so mistakes surface at boot.

func (StructSchema[T]) Check

func (s StructSchema[T]) Check(v T) error

Check implements Schema.

func (StructSchema[T]) Describe

func (s StructSchema[T]) Describe(text string) StructSchema[T]

Describe sets a description used by schema exports.

func (StructSchema[T]) Field added in v0.20.0

func (s StructSchema[T]) Field(key string) (reflect.StructField, bool)

Field returns the struct field of T that key parses into, for tools that map schema keys to other types (the admin panel copies them to models).

func (StructSchema[T]) GoType

func (StructSchema[T]) GoType() reflect.Type

GoType implements AnySchema.

func (StructSchema[T]) Keys

func (s StructSchema[T]) Keys() []string

Keys returns the shape keys in order.

func (StructSchema[T]) Nullable

func (s StructSchema[T]) Nullable() StructSchema[T]

Nullable allows null.

func (StructSchema[T]) Optional

func (s StructSchema[T]) Optional() StructSchema[T]

Optional allows the key to be absent.

func (StructSchema[T]) Parse

func (s StructSchema[T]) Parse(in any) (T, error)

Parse implements Schema.

func (StructSchema[T]) Refine

func (s StructSchema[T]) Refine(fn func(T) error) StructSchema[T]

Refine adds a cross-field check; return FieldError to point at a field, or FieldErrorKey for a translatable message.

func (StructSchema[T]) Strict

func (s StructSchema[T]) Strict() StructSchema[T]

Strict rejects keys that are not in the shape.

func (StructSchema[T]) Transform

func (s StructSchema[T]) Transform(fn func(T) T) StructSchema[T]

Transform maps the parsed value.

type TimeSchema

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

TimeSchema parses times from RFC 3339 strings (plus the HTML datetime-local and date formats by default).

func Time

func Time() TimeSchema

Time returns a schema for time.Time.

func (TimeSchema) After

func (s TimeSchema) After(t time.Time) TimeSchema

After requires the time to be strictly after t.

func (TimeSchema) Before

func (s TimeSchema) Before(t time.Time) TimeSchema

Before requires the time to be strictly before t.

func (TimeSchema) Check

func (s TimeSchema) Check(v time.Time) error

Check implements Schema.

func (TimeSchema) Default

func (s TimeSchema) Default(v time.Time) TimeSchema

Default uses v when the key is absent.

func (TimeSchema) Describe

func (s TimeSchema) Describe(text string) TimeSchema

Describe sets a description used by schema exports.

func (TimeSchema) GoType

func (TimeSchema) GoType() reflect.Type

GoType implements AnySchema.

func (TimeSchema) Layouts

func (s TimeSchema) Layouts(layouts ...string) TimeSchema

Layouts replaces the accepted layouts.

func (TimeSchema) Message

func (s TimeSchema) Message(code, message string) TimeSchema

Message overrides the message for an issue code.

func (TimeSchema) Nullable

func (s TimeSchema) Nullable() TimeSchema

Nullable allows null.

func (TimeSchema) Optional

func (s TimeSchema) Optional() TimeSchema

Optional allows the key to be absent.

func (TimeSchema) Parse

func (s TimeSchema) Parse(in any) (time.Time, error)

Parse implements Schema.

func (TimeSchema) Refine

func (s TimeSchema) Refine(fn func(time.Time) error) TimeSchema

Refine adds a custom check.

Jump to

Keyboard shortcuts

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