validate

package
v1.1.68-test Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: MIT Imports: 15 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package validate is the runtime validation subsystem — the Go equivalent of the Joi validation the TS service runs on create/patch bodies. It implements the DECLARATIVE rule set (required, default, valid-enum, min/max, integer, pattern, type) that the plan identifies as ~88% mechanically mappable from the Joi schemas, plus a Custom hook for the irreducible `.custom()`/`.when()` rules. Schemas are registered per resource kind and applied by the CRUD engine.

The declarative rules here are hand-authored for the ported resources; the intended end-state is to have nodelibs/schema/joi-to-go emit these Schemas directly from the Joi source of truth (see port-to-go.md "Validation").

Index

Constants

This section is empty.

Variables

View Source
var ErrSyntax = errors.New("invalid JSON")

ErrSyntax is returned for a body that is not valid JSON.

Functions

func Assign

func Assign(field reflect.Value, val any)

Assign writes a value into a field the way the walk writes a normalized result: a value of the field's type, a pointer to one, a convertible scalar, a time, or a generic tree.

func DeepCopy

func DeepCopy(v reflect.Value) reflect.Value

DeepCopy copies a value so the result shares nothing mutable with the source. A Wrapper is rebuilt around a copy of what it holds. The decoder uses it when a tree source hands it an in-process value of the field's own type: the row being built must not write through to wherever that value came from.

func Field

func Field(ptr any, jsonName string) (reflect.Value, bool)

Field returns the addressable field of a struct pointer by its json name, for a container custom that is written once for several types (reflectively).

func FieldOf

func FieldOf(v reflect.Value, jsonName string) (reflect.Value, bool)

FieldOf is Field on an addressable struct value: the settable field for a json name, through embedded structs and inline columns, allocating what it must.

func Get

func Get(obj any, jsonName string) any

Get reads a field of the object a container custom runs on, in the form the custom can work with: a scalar as itself, a struct as a pointer to it, a map with interface values as map[string]any (sharing the storage), nil when absent or null.

func ISODate

func ISODate(s string) (string, bool)

ISODate is Joi's string isoDate() with convert: the value as JS Date.toISOString() renders it; false when not an ISO date.

func ImmutableFields

func ImmutableFields(t reflect.Type) []string

ImmutableFields returns the top-level object field names (json keys) of the type's schema that are marked `readOnly` (server-owned: id/version/created/ lastModified/links, alias, keys, …) or `unmodifiable` (client-settable on create but fixed after: provider, region, …). These are exactly the fields the merge path must pin to the STORED value so a PATCH/PUT cannot change them — letting the engine enforce immutability from the schema instead of every handler having to remember to list them in RetainProps. Result is cached per type; nil when the schema root is not a plain object (e.g. an alternatives), so the caller falls back to its declared RetainProps.

func IndexPath

func IndexPath(i int) string

IndexPath builds a path segment for array element i, for a caller outside this package composing a base path (see Rule.ValidateAt / Rule.ApplyAt). Using it rather than strconv.Itoa is what keeps the segment typed as a NUMBER in the reported path.

func IsDomain

func IsDomain(domain string, tlds bool) bool

IsDomain is isDomain for callers outside the engine — the data-service's `domain` path-param rule, which Joi writes as an alternatives of hostname and .domain(opts) and which had grown its own hand-rolled copy of this grammar.

func IsISODate

func IsISODate(s string) bool

IsISODate is Joi's isoDate test, for a check made outside a schema walk.

func JSLen

func JSLen(s string) int

JSLen is JavaScript's String.prototype.length: the number of UTF-16 code units, NOT runes and NOT bytes.

Joi's .min/.max/.length count what JS counts, so a character outside the BMP (emoji, most CJK extensions, many scripts) counts as TWO. Counting runes let this port accept a 200-emoji value against a 250-"character" cap that TS rejects at 400 — i.e. up to 2x the documented limit on EVERY string rule in the schema set, persisting values TS's own validator considers illegal.

func JSTrim

func JSTrim(s string) string

JSTrim is JavaScript's String.prototype.trim, whose whitespace set is NOT the same as Go's unicode.IsSpace. Two characters differ, in opposite directions:

U+FEFF (ZWNBSP/BOM) — JS strips it, Go does not
U+0085 (NEL)        — Go strips it, JS does not

Because .trim() runs on every trimmed string BEFORE the length and pattern rules and the result is what gets PERSISTED, the disagreement changed both which values were accepted and what was stored: a leading BOM survived here and was stripped there, and vice versa for NEL.

The set is ECMA-262 WhiteSpace + LineTerminator.

func Nested

func Nested(original any, verr *Error) error

Nested wraps a sub-schema failure for return from a custom (see the type doc). A nil inner error returns nil, so a caller can pass a Validate result straight through.

func Num

func Num(f float64) *float64

Num returns a *float64 for rule bounds.

func OrderedKeys

func OrderedKeys(v any, h *Helper, rel ...any) []string

OrderedKeys returns v's keys the way `Object.keys(v)` orders them in the TS service: the order the request body listed them. rel addresses an object NESTED under the one the custom runs on (object keys as strings, array indices as ints); omit it for the value the custom was handed.

v must be map-shaped — an object the engine keeps as a map, which is what a custom reading keys by name is looking at. An object decoded into a STRUCT has no key order to ask about: its keys are its schema fields, and both evaluators already walk those in schema order.

Keys the wire order does not know — added by a default or a custom, or a value that never came from a body at all — fall in behind the ones it does, in the order a jsonb column hands them back. That is the right fallback rather than a plain sort: the order-less objects this engine sees are stored rows (the PATCH merge tree), and TS reads those out of a jsonb column, so jsonb's order IS its insertion order. A lexicographic fallback split the verdict on PATCH for `cpln_z` vs `cpln_aa`, where the two orders disagree.

func Peel

func Peel(v reflect.Value) (reflect.Value, bool)

Peel follows pointers and wrappers to the value they hold, without allocating; ok is false at a nil pointer or a null wrapper.

func PeelForWrite

func PeelForWrite(v reflect.Value) (reflect.Value, bool)

PeelForWrite is Peel that ALLOCATES: a nil pointer is filled in and a null wrapper opened, so the caller gets a settable inner value. It is how a caller materializes a subtree the body omitted — the Go equivalent of TS assigning `req.body.status = {}` before Joi runs, which is what makes the schema's nested defaults land there.

func RegisterTypeRule

func RegisterTypeRule(t reflect.Type, fn func() *Rule)

RegisterTypeRule attaches a rule to a type by identity. Panics on a duplicate registration for the same type, which would make the winner load-order dependent.

func ServerColumns

func ServerColumns(t reflect.Type) []string

ServerColumns returns the json names of a struct type's `validate:"-"` fields — columns the engine round-trips (scan + serialize + carried through the merge) but that are NOT part of the write schema. A request body may not set them: the handler rejects any that a client sends, the way TS's closed schemas reject them as unknown keys once the handler has stripped them from the merge base (e.g. serviceaccount `tokens`, org `account_id`). Cached per type. Top-level fields only, which is what every such column is.

func Set

func Set(obj any, jsonName string, val any)

Set writes a value into a field (or map key) of the object a container custom runs on. A struct pointer, a generic tree or a scalar are all accepted.

func Str

func Str(obj any, jsonName string) string

Str reads a string field of the object a container custom runs on — a map on the generic evaluator, a struct pointer on the typed walk — by json name.

func Sub

func Sub[T any](obj any, jsonName string) *T

Sub reads a struct or slice field as a typed pointer, nil when absent, null, or not of that type.

func ToFloat

func ToFloat(v any) (float64, bool)

ToFloat coerces a decoded JSON number (or a numeric string, as convert:true does) to float64. For customs that have to do arithmetic on a value the schema has already accepted.

Types

type AltCase

type AltCase struct {
	IsEq      any
	Is        *Rule
	Then      *Rule
	Otherwise *Rule
}

AltCase holds one alternatives().conditional branch. IsEq / Is carry the same distinction they do on When — see that type's doc.

type Bytes

type Bytes []byte

Bytes is a JSON document.

type Case

type Case struct {
	Name  string
	Input any
	Ctx   *Context
	Prefs Prefs

	// WantErr, if non-empty, asserts the case is rejected and the error message
	// contains this substring (Joi test style: expect(error.message).toContain(...)).
	WantErr string

	// Want, if non-nil, asserts the accepted+normalized output deep-equals this
	// value (Joi: expect(result.value).toEqual(...)). Numbers should be float64.
	Want any

	// Check is an optional post-normalization assertion for cases where a full
	// deep-equal is awkward; return a non-nil error to fail.
	Check func(out any) error
}

Case is one parity vector: an input body + context/prefs → expect accept (with an optional normalized-output assertion) or reject (with a message substring).

func (Case) Run

func (c Case) Run(rule *Rule) error

Run validates Case.Input against rule and checks the expectation. It returns a descriptive error on mismatch (nil = pass).

type Context

type Context struct {
	Org    string
	Gvc    string
	Method string // POST | PUT | PATCH
}

Context is the Joi validation context (makeJoiContext in base.ts): org, gvc and HTTP method. It is threaded to every CustomFn via *Helper.

type CustomFn

type CustomFn func(value any, h *Helper) (any, error)

CustomFn is a `.custom((value, helpers) => ...)` port. It receives the current (already type-coerced) value and returns the possibly-transformed value, or an error to fail validation. Returning a *Error preserves type/path; any other error is wrapped with the field's path.

func CustomT

func CustomT[T any](fn func(*T, *Helper) error) CustomFn

CustomT is a custom that receives a pointer to the typed container it is declared on (an object or array rule) and may mutate it in place. It is the typed form of Custom for containers; the generic evaluator refuses it, and the typed walk refuses a Custom written for a map or []any, so neither can silently skip the other's hook.

type Decoded

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

Decoded is a struct filled from a body plus the record of what the body held. It is handed to Validate once the caller has done whatever it does between decoding and validating (the pre-schema seams rewrite the row there).

func DecodeInto

func DecodeInto(dst any, src Source) (*Decoded, error)

DecodeInto fills dst (a pointer to a struct) from src. dst's existing contents are kept where the body is silent, so a caller can pre-populate server-owned fields.

func (*Decoded) MarkPresent

func (d *Decoded) MarkPresent(jsonName string)

MarkPresent records a top-level key as present even though the body did not carry it, so the walk descends into it (applying its nested defaults) and an apply-merge treats it as written rather than copying the stored value over. TS expresses this by rewriting req.body before Joi runs (volumeset.ts:914 `if (!req.body.status) req.body.status = {}`); a Go struct field is always physically there, so assignment alone cannot say it.

func (*Decoded) Present

func (d *Decoded) Present(jsonName string) bool

Present reports whether a top-level key was in the body, or has since been set on the struct (the same notion of presence Validate uses).

func (*Decoded) Validate

func (d *Decoded) Validate(rule *Rule, ctx *Context, prefs Prefs) *Error

Validate runs rule over the decoded struct. Fields the body did not carry but a caller set between DecodeInto and Validate count as present (a pre-schema hook writes the row the same way TS rewrites req.body before Joi runs).

func (*Decoded) ValidateAt

func (d *Decoded) ValidateAt(rule *Rule, base []string, ctx *Context, prefs Prefs) *Error

ValidateAt is Validate with every error reported UNDER base — for a struct that is one field of a larger document (a command's `spec`).

func (*Decoded) Value

func (d *Decoded) Value() any

Value returns the decoded struct (the pointer DecodeInto was given).

type Detail

type Detail struct {
	Message string         `json:"message"`
	Path    []any          `json:"path"`
	Type    string         `json:"type"`
	Context map[string]any `json:"context,omitzero"`
}

Detail is one element of the Joi error.details[] array.

Path is []any, not []string, because Joi's path mixes types: an object key is a string and an ARRAY INDEX is a number (`["spec","ports",0,"protocol"]`). A client walking the path to point at the offending field — which is the only reason the field exists — indexes an array with the number, so emitting "0" there is not a cosmetic difference.

type EnumValuer

type EnumValuer interface{ EnumValues() []string }

EnumValuer is implemented by a typed-string enum whose allowed values cannot be enumerated by reflection; the reflection bridge calls EnumValues() to add .Valid(...) for the field's base rule.

type Error

type Error struct {
	Type    string
	Message string
	Path    []string
	Ctx     map[string]any
	// contains filtered or unexported fields
}

Error is a validation failure. It carries the Joi error type, human message, and the dot/bracket path so the HTTP layer can render error.details[] at parity with the TS service (isDataInvalid → {status, message, details}).

func CustomErrorAt

func CustomErrorAt(path []string, value any, msg string) *Error

CustomErrorAt builds the error Joi raises when a `.custom()` at `path` throws a plain Error: an `any.custom` carrying the wrapped message and the usual label/key/value/error context. Exported for the passes that run OUTSIDE the schema walk but must answer in the schema's envelope — the data-service expands links before validating, where TS expands inside a Joi custom, and a bare error there escapes the envelope entirely.

func Decode

func Decode[T any](src Source, ctx *Context, prefs Prefs) (*T, *Error)

Decode is DecodeInto + Validate against the type's own schema, for callers with nothing to do in between.

func Validate

func Validate(rule *Rule, value any, ctx *Context, prefs Prefs) (any, *Error)

Validate runs a rule against a value with the given context/prefs, returning the normalized value and a *Error (nil on success). It is the single-value entry point (Joi's schema.validate(value, options)); Schema.ApplyCtx is the in-place object entry used by the CRUD engine.

func (*Error) Details

func (e *Error) Details() []Detail

Details returns the details[] array (abortEarly → a single element).

func (*Error) Error

func (e *Error) Error() string

type ExtrasMarker

type ExtrasMarker interface{ ExtrasMarker() }

ExtrasMarker is implemented by the map type an `unknown(true)` object keeps its undeclared keys in (base.Extras). A struct with such a field receives allowed unknown keys there; a struct without one has them stripped.

type FieldRule

type FieldRule struct {
	Path     string // e.g. "spec.initialCapacity"
	Required bool
	// Default is applied when the field is absent/nil. A string of the form
	// "$name" references another top-level field's value (Joi.ref).
	Default any
	Enum    []any          // valid() — allowed values
	Min     *float64       // numeric minimum (inclusive)
	Max     *float64       // numeric maximum (inclusive)
	Integer bool           // must be a whole number
	Pattern *regexp.Regexp // string must match
	Type    string         // "number" | "string" | "object" | "array" | "boolean"
}

FieldRule is the set of declarative constraints on one field (dot-path).

type Helper

type Helper struct {
	Ctx      *Context
	Original any
	Path     []string
	// contains filtered or unexported fields
}

Helper is the second argument to a CustomFn — Joi's `helpers`. Original is the pre-coercion value (helpers.original); Ctx is prefs.context.

func (*Helper) Ancestor

func (h *Helper) Ancestor(n int) map[string]any

Ancestor returns the object n levels above the value being validated, as a generic map: 0 is the immediate parent object, 1 its parent, and so on — Joi's helpers.state.ancestors. nil when there is no such level.

Arrays do not count as a level (an element shares its array's state), so a custom on `spec.containers[0]` reads the container with Ancestor(0), the spec with Ancestor(1) and the document with Ancestor(2). It exists because a cross-field check often has to read a grandparent — a container rule needing the workload's own tags — which the immediate-parent-only view could not reach at all.

func (*Helper) ErrorAt

func (h *Helper) ErrorAt(rel []any, value any, typ, format string, args ...any) *Error

ErrorAt is Errorf anchored at a path RELATIVE to the node being validated, for a cross-field check that must report against a NESTED field rather than the object it runs on. rel segments are object keys (string) or array indices (int); value is the value at that path (Joi's context.value).

It exists because a check needing the parent's data still has to blame the child: the container cross-checks read the workload's options, so they run on the workload, but Joi reports them at `spec.containers[0]` — which is the field the caller has to fix, and the only thing an editor can highlight.

func (*Helper) Errorf

func (h *Helper) Errorf(typ, format string, args ...any) *Error

Errorf raises a typed validation error anchored at the field being validated (helpers.error / thrown Error in Joi customs).

func (*Helper) Label

func (h *Helper) Label() string

Label is the field's Joi label ("data.payload", or "value" at the root) — for a custom composing its own message, so it names the field the caller wrote instead of a hardcoded one.

func (*Helper) Present

func (h *Helper) Present(key string) bool

Present reports whether key was set on the object a container custom runs on: sent by the client, or given a default. Always false for a leaf custom.

func (*Helper) WithCtx

func (h *Helper) WithCtx(e *Error, kv ...any) *Error

WithCtx adds context keys to an error a custom is about to return, for the cases where a custom has to raise one of Joi's OWN error types by hand and must carry the context that type always has (a string.pattern.base carries `regex` and `value`).

type JSRegex

type JSRegex string

JSRegex is a regex carried as its JavaScript SOURCE, for describe() and messages where the Go pattern is not the pattern the schema was written with.

type NestedValidationError

type NestedValidationError struct {
	Original any
	Err      *Error
}

NestedValidationError is the failure of a schema run INSIDE a custom — base.ts's checkImageName does `throw ImageName.validate(v).error`, and Joi serializes that thrown ValidationError into `context.error` as {_original, details}, where a plain Error serializes as {}. A custom returns this to say it threw the former.

func (*NestedValidationError) Error

func (e *NestedValidationError) Error() string

type Prefs

type Prefs struct {
	// There is deliberately no `presence:'optional'` preference: in Joi it only sets
	// the DEFAULT presence, which is already optional, and never relaxes a key's
	// explicit .required() — so it is a no-op, and a port that relaxed requireds
	// under it accepted bodies TS rejects.
	// AllowUnknown maps to allowUnknown:true — keep unknown keys.
	AllowUnknown bool
	// StripUnknown maps to stripUnknown:true — drop unknown keys (wins over
	// AllowUnknown, matching Joi).
	StripUnknown bool
}

Prefs are per-call-site preference overrides (the options object passed to schema.validate). The zero value = Joi defaults (reject unknown, honour presence). Specific TS call sites set these (workload.ts:282, deployment processor, secret.ts, orgMember invite, inviteToOrg).

type Ref

type Ref struct{ Key string }

Ref is a Joi.ref('sibling') — resolved against the immediate parent object.

func RefTo

func RefTo(key string) *Ref

RefTo builds a Joi.ref.

type Refiner

type Refiner interface {
	Refine(obj map[string]any, h *Helper) error
}

Refiner lets a struct type attach an object-level cross-field custom (the "complex parts of Joi" — cross-field validation). obj is the validated object (post type-coercion, siblings readable/mutatable); h carries the Context. Return an error to fail; mutating obj is honoured. Equivalent to the .Refine() builder, applied automatically when a reflected struct type implements it.

type Rule

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

Rule is a compiled Joi schema node. Build via the constructors (String, Number, …) and fluent methods; each fluent method returns a copy (Joi schemas are immutable), so shared sub-schema symbols can be safely re-decorated.

func Alternatives

func Alternatives(alts ...*Rule) *Rule

Alternatives builds Joi.alternatives().try(alts...).

func Any

func Any() *Rule

Any builds Joi.any().

func Array

func Array(items ...*Rule) *Rule

Array builds Joi.array().items(items...).

func Boolean

func Boolean() *Rule

Boolean builds Joi.boolean().

func DateRule

func DateRule() *Rule

DateRule builds Joi.date(); normalized output is an ISO-8601 millis UTC string (matching JSON.stringify of a JS Date).

func FromType

func FromType(t reflect.Type) *Rule

FromType builds the *Rule for a struct type (following a leading pointer) by pure reflection over its fields + `validate:` tags. Field types implementing Validator resolve to their own rule; a resource's ValidationRule typically calls Reflect(self) (which routes here) then layers object-level .Refine/.Xor.

func Number

func Number() *Rule

Number builds Joi.number().

func Object

func Object(keys map[string]*Rule) *Rule

Object builds Joi.object(keys). A nil map is Joi.object() (any keys subject to unknown policy). Go maps have no order, so the keys are sorted for determinism; use ObjectOrdered where the DECLARATION order matters.

func ObjectOrdered

func ObjectOrdered(order []string, keys map[string]*Rule) *Rule

ObjectOrdered builds Joi.object(keys) preserving the given key order.

abortEarly means only the FIRST failing key is reported, so the order decides WHICH error the caller sees. Joi walks keys in schema-declaration order; the canonical structs are declared in that same order, so a rule reflected from a struct must keep its field order rather than sort (a body missing both `name` and `data` reported "data" where TS reports "name").

func RefineT

func RefineT[T any](r *Rule, fn func(*T, *Helper) error) *Rule

RefineT attaches a typed object-level cross-field check to an object rule.

func Reflect

func Reflect(v any) *Rule

Reflect builds the pure struct-tag rule for v's type (following a pointer), WITHOUT invoking that type's own ValidationRule — so a resource's ValidationRule can call Reflect(self) then layer object-level .Refine/.Xor without recursing. Field types that themselves implement Validator DO resolve to their own rule (via baseRuleForType).

func String

func String() *Rule

String builds Joi.string(). By default rejects ” (Joi string.empty) unless .Allow("").

func (*Rule) Allow

func (r *Rule) Allow(vals ...any) *Rule

Allow sets .allow(vals...) — these bypass all other checks and pass verbatim.

func (*Rule) Append

func (r *Rule) Append(keys map[string]*Rule) *Rule

Append is Joi's schema.append(keys) — same as Keys for our purposes.

func (*Rule) ApplyAt

func (r *Rule) ApplyAt(base []string, obj map[string]any, ctx *Context, prefs Prefs) error

ApplyAt validates obj against the rule with every error reported UNDER base — for validating a sub-document with another schema. TS gets this for free by embedding the sub-schema in the parent (group.ts:472 forks `memberQuery` to the org_member query schema), so its errors already read `memberQuery.spec.terms[0].property`; applying the sub-schema separately without a base path reports at the root and names a field the caller cannot find in their request.

func (*Rule) Base64

func (r *Rule) Base64() *Rule

Base64 is `.base64()` with Joi's defaults (padding required, not url-safe).

func (*Rule) Conditional

func (r *Rule) Conditional(ref string, b AltCase) *Rule

Conditional sets alternatives().conditional(ref, {is, then, otherwise}).

func (*Rule) Custom

func (r *Rule) Custom(fn CustomFn) *Rule

Custom appends a .custom(fn).

func (*Rule) CustomTyped

func (r *Rule) CustomTyped(fn CustomFn) *Rule

CustomTyped attaches a container custom that handles the typed form: on the typed walk it receives a POINTER to the object/array (see CustomT for the checked generic form), on the generic evaluator the map/[]any. For a custom that inspects its argument by reflection and so serves both.

func (*Rule) Dedupe

func (r *Rule) Dedupe(by ...string) *Rule

Dedupe sets TS's `.custom(makeUnique(by?))` semantics (base.ts:138-149): a duplicate is SILENTLY DROPPED (keep first, _.uniq/_.uniqBy), never rejected. Distinct from Unique, which rejects — a field must map to whichever its Joi schema uses.

func (*Rule) Default

func (r *Rule) Default(v any) *Rule

Default sets .default(v). v may be a literal, a *Ref (Joi.ref), or a func() any.

func (*Rule) Describe

func (r *Rule) Describe() any

Describe returns the rule's Joi `describe()` document.

func (*Rule) Description

func (r *Rule) Description(text string) *Rule

Description sets .description(text). It carries no validation behaviour; it is reported by Describe() (GET /catalog/schema/{kind}).

func (*Rule) Domain

func (r *Rule) Domain() *Rule

func (*Rule) DomainTLDs

func (r *Rule) DomainTLDs() *Rule

DomainTLDs is .domain(opts) — Joi checks the last segment against the bundled IANA list as soon as ANY options object is passed, `{minDomainSegments:2}` included, and only `tlds:false` turns it back off. Bare .domain() skips the list, so the two are genuinely different rules and the call site has to pick.

func (*Rule) Email

func (r *Rule) Email() *Rule

func (*Rule) Forbidden

func (r *Rule) Forbidden() *Rule

Forbidden marks the field .forbidden().

func (*Rule) Fork

func (r *Rule) Fork(key string, fn func(*Rule) *Rule) *Rule

Fork replaces one key's schema (a narrowed Joi.fork over a single path).

func (*Rule) FromNumber

func (r *Rule) FromNumber() *Rule

FromNumber coerces a JSON number input to its string form before string rules run, porting the TS JoiNumberToString extend (workload.ts WholeNumberOrPercent / IntegerOrPercent, master f94fb6d78).

func (*Rule) Id

func (r *Rule) Id(name string) *Rule

Id sets .id(name) — Joi's schema identifier, reported as flags.id by describe(). It carries no validation behaviour.

func (*Rule) Integer

func (r *Rule) Integer() *Rule

func (*Rule) Invalid

func (r *Rule) Invalid(vals ...any) *Rule

Invalid sets .invalid(vals...).

func (*Rule) Iso

func (r *Rule) Iso() *Rule

Iso sets Joi.date().iso(): the value must be a STRING in ISO-8601 (Joi's own isoDate grammar, see isodate.go), so a slash date, a month name, a number and an epoch-millis string are all rejected. It used to return the rule unchanged, which accepted all of them.

func (*Rule) Items

func (r *Rule) Items(items ...*Rule) *Rule

Items sets .items(items...).

func (*Rule) Keys

func (r *Rule) Keys(keys map[string]*Rule) *Rule

Keys replaces/extends the object's keyed sub-schemas.

func (*Rule) Label

func (r *Rule) Label(l string) *Rule

Label overrides the error label.

func (*Rule) Length

func (r *Rule) Length(n int) *Rule

Length sets .length(n) by type.

func (*Rule) Lowercase

func (r *Rule) Lowercase() *Rule

func (*Rule) Max

func (r *Rule) Max(n int) *Rule

Max sets .max(n) by type.

func (*Rule) MaxNum

func (r *Rule) MaxNum(f float64) *Rule

func (*Rule) MaxRef

func (r *Rule) MaxRef(key string) *Rule

MaxRef sets .max(Joi.ref(key)) for numbers.

func (*Rule) Message

func (r *Rule) Message(text string) *Rule

Message is Joi's `.message(text)`: it replaces the message of the rule applied immediately before it, leaving the error type and context alone. Hand-rolling the override as a .Custom() instead (the shape this replaced) loses the type and the limit/regex context that clients rendering their own message read.

func (*Rule) Messages

func (r *Rule) Messages(byType map[string]string) *Rule

Messages is Joi's `.messages({type: text})`: it replaces the message of every error of that TYPE the rule raises — including the presence errors (any.required, any.unknown) its parent object raises for it, which no `.message()` can reach.

func (*Rule) Meta

func (r *Rule) Meta(m map[string]any) *Rule

Meta appends a .meta({...}) the engine does not act on (type/pointer/hidden — codegen and UI hints). It is carried verbatim into Describe().

func (*Rule) Min

func (r *Rule) Min(n int) *Rule

Min sets .min(n): string length, number bound, or array length by type.

func (*Rule) MinNum

func (r *Rule) MinNum(f float64) *Rule

MinNum / MaxNum are Min / Max with a float64 bound, for limits outside int range (envoy's UInt64 caps at 2^64-1, which Joi computes as a float64).

func (*Rule) MinRef

func (r *Rule) MinRef(key string) *Rule

MinRef sets .min(Joi.ref(key)) for numbers.

func (*Rule) Nand

func (r *Rule) Nand(peers ...string) *Rule

Nand adds .nand(peers...) — peers must not all be present together.

func (*Rule) Negative

func (r *Rule) Negative() *Rule

func (*Rule) NumMax

func (r *Rule) NumMax(f float64) *Rule

NumMax sets a numeric maximum (float).

func (*Rule) NumMin

func (r *Rule) NumMin(f float64) *Rule

NumMin sets a numeric minimum (float, for non-integer bounds like precision).

func (*Rule) Optional

func (r *Rule) Optional() *Rule

Optional marks the field .optional().

func (*Rule) Or

func (r *Rule) Or(peers ...string) *Rule

Or adds .or(peers...) — at least one of peers must be present.

func (*Rule) Oxor

func (r *Rule) Oxor(peers ...string) *Rule

Oxor adds .oxor(peers...) — at most one of peers may be present.

func (*Rule) Pattern

func (r *Rule) Pattern(key, val *Rule) *Rule

Pattern adds a .pattern(keySchema, valSchema). Several may be attached; they are tried in the order they were added.

func (*Rule) Port

func (r *Rule) Port() *Rule

func (*Rule) Positive

func (r *Rule) Positive() *Rule

func (*Rule) Precision

func (r *Rule) Precision(n int) *Rule

Precision sets .precision(n) — rounds to n decimal places (Joi convert).

func (*Rule) ReadOnly

func (r *Rule) ReadOnly() *Rule

ReadOnly marks .meta({readOnly:true}).

func (*Rule) Refine

func (r *Rule) Refine(fn func(map[string]any, *Helper) error) *Rule

Refine attaches an object-level cross-field custom (Joi `.custom()` on the object). obj is the validated object (post type-coercion, siblings readable / mutatable); h carries the validation Context. Return an error (a *Error or h.Errorf) to fail. It is the builder form of the old Refiner interface, used inside a resource's ValidationRule to layer cross-field checks onto Reflect().

func (*Rule) Regex

func (r *Rule) Regex(re *regexp.Regexp) *Rule

Regex sets .regex(re) / .pattern(re). name is the optional named-pattern label.

func (*Rule) RegexAs

func (r *Rule) RegexAs(re *regexp.Regexp, jsSource string) *Rule

RegexAs is Regex with an explicit JavaScript source for the message and the describe document — for a Joi pattern RE2 cannot express verbatim (lookahead). The Go regexp still does the matching, so it must be equivalent for the inputs that reach it; anything it cannot express belongs in a guard beside it.

func (*Rule) RegexInvert

func (r *Rule) RegexInvert(re *regexp.Regexp) *Rule

RegexInvert sets .pattern(re, {invert:true}) / .regex(re, {invert:true}).

func (*Rule) Required

func (r *Rule) Required() *Rule

Required marks the field .required().

func (*Rule) Single

func (r *Rule) Single() *Rule

Single sets .single() — a non-array scalar is coerced to a one-element array before item validation (Joi array.single with convert:true).

func (*Rule) Sort

func (r *Rule) Sort() *Rule

Sort sets .sort() (ascending, matching Joi's default order).

func (*Rule) SortBy

func (r *Rule) SortBy(field string) *Rule

SortBy adds Joi's `.sort({ by: field })` — order the elements by one of their object keys, ascending. Distinct from Sort(), which orders whole values.

func (*Rule) Strip

func (r *Rule) Strip() *Rule

Strip is Joi's `.strip()`: the key is validated as usual and then removed from the result, defaults included, so it is also invisible to xor/nand/oxor and object.min. It lets a retired field keep validating on write while never being stored or echoed.

func (*Rule) StripUnknown

func (r *Rule) StripUnknown() *Rule

StripUnknown sets .unknown('strip') behaviour on the object.

func (*Rule) Trim

func (r *Rule) Trim() *Rule

func (*Rule) Try

func (r *Rule) Try(alts ...*Rule) *Rule

Try sets .try(alts...).

func (*Rule) URI

func (r *Rule) URI() *Rule

func (*Rule) URIScheme

func (r *Rule) URIScheme(schemes ...string) *Rule

URIScheme is `.uri({scheme: [...]})`. Joi regenerates the whole URI grammar with the scheme production replaced, so a failure is reported as string.uriCustomScheme (with the alternation in context) rather than the plain string.uri.

func (*Rule) UUID

func (r *Rule) UUID() *Rule

func (*Rule) Unique

func (r *Rule) Unique(by ...string) *Rule

Unique sets .unique(); by is an optional key for uniqueness by property. This is Joi's `.array().unique()` — a REJECT on a duplicate (array.unique error).

func (*Rule) UniqueComparing

func (r *Rule) UniqueComparing(field string) *Rule

UniqueComparing is `.unique((a, b) => a[field] === b[field])` — Joi's FUNCTION comparator. It rejects like Unique but, unlike the string-path spelling, its error carries no `path` context, because Joi has no path to report for a function.

func (*Rule) Unknown

func (r *Rule) Unknown(allow bool) *Rule

Unknown sets the object's unknown-key policy: true → keep unknown keys.

`.unknown(false)` clears the flag rather than setting a reject POLICY, because that is what Joi does — `unknown(false)` writes the flag's own default, and Joi drops a flag equal to its default, so the object falls back to `Common.default(flags.unknown, prefs.allowUnknown)` and an allowUnknown preference still applies. Recording it as an explicit reject made `.unknown(false)` block the preference.

func (*Rule) Unmodifiable

func (r *Rule) Unmodifiable() *Rule

Unmodifiable marks .meta({unmodifiable:true}).

func (*Rule) Uppercase

func (r *Rule) Uppercase() *Rule

func (*Rule) Valid

func (r *Rule) Valid(vals ...any) *Rule

Valid sets .valid(vals...) — only these values are accepted (any.only).

func (*Rule) ValidateAt

func (r *Rule) ValidateAt(base []string, value any, ctx *Context, prefs Prefs) (any, error)

ApplyCtx validates obj against the schema, threading the Joi validation context (org/gvc/method) and per-call-site Prefs. For a combinator Root it runs the engine and writes the normalized (coerced/defaulted/stripped) result back into obj in place. For the legacy Fields path it ignores ctx/prefs and runs the declarative checks. Returns nil or a *Error (parity error body). ValidateAt validates a single (non-object) value against the rule, reporting under base. The scalar counterpart of ApplyAt, for a check that happens outside the schema walk but must answer as though it were inside it.

func (*Rule) When

func (r *Rule) When(ref string, w When) *Rule

When appends a `.when(ref, …)` conditional.

func (*Rule) Xor

func (r *Rule) Xor(peers ...string) *Rule

Xor adds .xor(peers...) — exactly one of peers must be present.

type Schema

type Schema struct {
	Root *Rule

	Fields []FieldRule
	// Custom validators run after declarative checks; return an error to fail.
	// They may mutate obj (e.g. Joi.custom coercions like fileSystemType→pc).
	Custom []func(obj map[string]any) error
	// contains filtered or unexported fields
}

Schema is a resource's validation definition. Two authoring styles coexist:

  • Root: a combinator *Rule (the Joi-parity engine, rule.go/eval.go) — the target style all resources migrate to.
  • Fields/Custom: the legacy declarative FieldRule path (retained until each fan-out agent migrates its resource to a Root rule).

When Root != nil it takes precedence.

func For

func For[T any]() *Schema

For is generic sugar: OfType for the type parameter T.

func ObjectSchema

func ObjectSchema(root *Rule) *Schema

ObjectSchema wraps a *Rule object as a top-level *Schema for Register/For.

func OfType

func OfType(t reflect.Type) *Schema

OfType returns the cached *Schema for a Go type (following pointers). If the type implements Validator, its ValidationRule() is the schema root; otherwise the reflected struct-tag rule is used (no custom validation — the fallback). The rule is built once, lazily, on first ApplyCtx.

func OfTypeIfValidator

func OfTypeIfValidator(t reflect.Type) *Schema

OfTypeIfValidator returns OfType(t) only when t (or *t) implements Validator, else nil. It is the transitional dispatch seam: runValidate prefers a type's own Validator schema when the type has been migrated, and falls back to the legacy kind-string registry (ForKind) otherwise — so migrating a kind is just "make its struct implement Validator", with no engine/handler coordination.

func (*Schema) Apply

func (s *Schema) Apply(obj map[string]any) error

Apply validates obj with default Joi prefs and an empty context. It is the legacy entry point (kept so existing callers compile); prefer ApplyCtx.

func (*Schema) ApplyCtx

func (s *Schema) ApplyCtx(obj map[string]any, ctx *Context, prefs Prefs) error

func (*Schema) ApplyValue

func (s *Schema) ApplyValue(v any, ctx *Context, prefs Prefs) (any, error)

ApplyValue validates a top-level value that need not be an OBJECT, returning the normalized result. express's json parser accepts an array as a body under strict mode and hands it to the route as-is, so a route whose TS twin passes req.body straight to Joi must be able to get Joi's own `object.base` for one — which the map-shaped ApplyCtx cannot express.

func (*Schema) Describe

func (s *Schema) Describe() any

Describe returns the schema's Joi `describe()` document. Nil for a legacy Fields-only schema (no combinator root).

func (*Schema) Rule

func (s *Schema) Rule() *Rule

Rule returns the schema's combinator root, forcing the lazy build. Returns nil for a legacy Fields-only schema. Callers that need to derive a variant of a schema (e.g. the create fork) go through this rather than touching Root, which is unpopulated until the first ApplyCtx.

func (*Schema) UntypedContainerCustoms

func (s *Schema) UntypedContainerCustoms() []string

UntypedContainerCustoms lists the paths in a rule graph whose container customs were written for the generic shapes (Custom / Refine on an object or array rule). Such a rule can only run on the generic evaluator; a resource schema, which the write path runs on the row, must have none. A gate test asks this of every registered kind.

type Source

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

Source is a body to decode: Bytes or Tree. ordered reports whether the source can still say what order the keys came in — bytes can, an already-parsed tree cannot.

type Tree

type Tree struct{ V any }

Tree is an already-parsed document in encoding/json's generic shapes.

type Validator

type Validator interface{ ValidationRule() *Rule }

Validator is implemented by a type that defines its own validation rule. A resource struct returns its complete rule (typically Reflect(self) layered with object-level .Refine/.Xor); a leaf nominal type returns its own rule (e.g. String().Regex(cpuRe)). It is the single interface that replaces Register / RegisterType / RegisterCustom / RegisterPattern / RegisterObjectRules / RegisterRefine and the kind-string registry.

type When

type When struct {
	// IsEq is the literal condition (see the type doc). Mutually exclusive with Is.
	IsEq      any
	Is        *Rule
	Not       *Rule
	Then      *Rule
	Otherwise *Rule
}

When holds the branches of a `.when` clause.

The two condition forms are NOT interchangeable, because Joi treats them differently (compile.js exports.when: "Only apply required if this wasn't already a schema or a ref"):

IsEq — the TS `is: 'cpu'` LITERAL form. Compiled to `valid(lit).required()`, so an
       ABSENT sibling does not match.
Is   — the TS `is: Joi.string().regex(...)` SCHEMA form. Joi adds no .required(), so
       an absent sibling DOES match unless the schema itself is .Required().

Both shapes are live in the schema set — workloadOptions.ts:145 is a literal, envoyCommon.ts:8 is a schema — so the engine cannot pick one. Port a TS literal with IsEq; reach for Is only when the TS wrote a schema.

type Wrapper

type Wrapper interface {
	// InnerForWrite returns a pointer to the inner value, allocating it if needed,
	// and marks the wrapper as holding a value (not null).
	InnerForWrite() any
	// SetNull records an explicit JSON null.
	SetNull()
	// IsNull reports an explicit null.
	IsNull() bool
}

Wrapper is a container field type holding ONE inner value — the shape of a jsonb column wrapper. The decoder writes through it and the walk reads through it, so a row's `spec` column decodes straight into the typed spec the column carries.

Jump to

Keyboard shortcuts

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