validonce

package module
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2026 License: Apache-2.0 Imports: 14 Imported by: ? 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.

README

validonce for Go

Write cross-field validation rules once, next to a Go struct. The server enforces them, Huma publishes them in the OpenAPI document under x-validonce, and browser forms (React, Angular, Vue, plain HTML) enforce the same rules.

Install

go get github.com/metatoy/validonce/go

Needs Go 1.26 or later. The core package has no dependencies beyond the standard library. github.com/metatoy/validonce/go/humaonce adds Huma, and github.com/metatoy/validonce/go/playground adds go-playground/validator.

Example

type Signup struct {
	Plan     string  `json:"plan" enum:"free,pro"`
	Company  *string `json:"company,omitempty" nullable:"true"`
	Email    string  `json:"email" minLength:"1"`
	Start    string  `json:"start" format:"date"`
	End      *string `json:"end,omitempty" format:"date" nullable:"true"`
	Quantity int32   `json:"quantity"`
}

var signupRules = validonce.MustBuild[Signup](
	validonce.When(validonce.Eq("plan", "pro")).Require("company", validonce.Key("rules.company_required")),
	validonce.Cmp("end").Ge(validonce.Ref("start"), validonce.Key("rules.end_after_start")),
	validonce.Cmp("quantity").Ge(validonce.Val(1), validonce.Key("rules.quantity_min"),
		validonce.Params(map[string]any{"min": 1})),
)

// Publish the rules as x-validonce on the component schema.
func (Signup) TransformSchema(_ huma.Registry, s *huma.Schema) *huma.Schema {
	return humaonce.Transform(signupRules, s)
}

A request that breaks a rule gets 422 as application/problem+json, with the issues in a top-level validonce member. The full walk-through, including go-playground/validator, is in Getting started: Go.

Release tags for this module are go/vX.Y.Z.

License

Copyright 2026 Metatoy LLC. Licensed under the Apache License, Version 2.0 (see LICENSE and NOTICE).

Documentation

Overview

Package validonce evaluates and builds validonce rule sets (rule format v1).

Rules are data: the same JSON that the C#, Python and TypeScript implementations export under "x-validonce". Evaluate runs them against the wire form of an object (a decoded JSON map).

Index

Constants

View Source
const (
	RulesHeader        = "Validonce-Rules"
	RulesStatusHeader  = "Validonce-Rules-Status"
	RulesCurrentHeader = "Validonce-Rules-Current"
	StaleRulesType     = "https://schemas.metatoy.com/validonce/problems/stale-rules"
)

Header names and the problem type of the 412 response.

View Source
const DefaultProblemStatus = 422

DefaultProblemStatus is the status a failing rule set is reported with.

View Source
const Version = 1

Version is the rule format version this package implements.

Variables

This section is empty.

Functions

func CanonicalJSON added in v0.6.0

func CanonicalJSON(data []byte) (string, error)

CanonicalJSON returns the RFC 8785 form of a JSON text: keys sorted by UTF-16 code units, no whitespace, ECMAScript string and number forms. Every number is an IEEE 754 double, so 1.0 is 1 and -0 is 0.

func HashToByteSequence added in v0.6.0

func HashToByteSequence(hash string) (string, error)

HashToByteSequence writes sha256-<base64> as a Structured Field byte sequence, :<base64>:.

func ParseRulesHeader added in v0.6.0

func ParseRulesHeader(value string) []string

ParseRulesHeader parses a Validonce-Rules value (an RFC 9651 List of byte sequences) into sha256-<base64> hashes. It returns nil when the value is empty or does not parse.

func ParseUntil added in v0.6.0

func ParseUntil(until string) (time.Time, error)

ParseUntil parses an accepted hash's expiry: an RFC 3339 datetime with an offset.

func RuleSetHash added in v0.6.0

func RuleSetHash(data []byte) (string, error)

RuleSetHash returns the identity of the rule set in data (the x-validonce JSON). The rule set must be valid (it is parsed first); it is hashed exactly as given, so hash the value as it is published.

func RuleSetsHashes added in v0.6.0

func RuleSetsHashes(document []byte) (map[string]string, error)

RuleSetsHashes returns the hash of every rule set in an OpenAPI 3.x document, keyed by the name of the component schema that carries it.

func RulesHeaderValue added in v0.6.0

func RulesHeaderValue(hashes ...string) (string, error)

RulesHeaderValue is the Validonce-Rules value a client sends.

func RulesStatusValue added in v0.6.0

func RulesStatusValue(current string) (string, error)

RulesStatusValue is the Validonce-Rules-Status value for a stale request.

func ValidateRules

func ValidateRules(rules []Rule) error

ValidateRules checks the structure of rules (kind-specific members, ops, types, conditions).

Types

type AcceptHash added in v0.6.0

type AcceptHash struct {
	Hash  string
	Until time.Time
}

AcceptHash is an extra hash treated as current (grace after a deploy), until Until when it is set.

type Builder

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

Builder is one rule under construction. Create them with When, Cmp, AtLeastOneOf and friends.

func AllOrNone

func AllOrNone(fields []string, opts ...Option) Builder

AllOrNone fails when some, but not all, fields are blank.

func AtLeastOneOf

func AtLeastOneOf(fields []string, opts ...Option) Builder

AtLeastOneOf fails when every field is blank.

func ExactlyOneOf

func ExactlyOneOf(fields []string, opts ...Option) Builder

ExactlyOneOf fails unless exactly one field is not blank.

type CmpBuilder

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

CmpBuilder is the first half of a compare rule.

func Cmp

func Cmp(field string) CmpBuilder

Cmp starts a compare rule with field on the left.

func (CmpBuilder) Eq

func (c CmpBuilder) Eq(r Operand, opts ...Option) Builder

Eq is "equal".

func (CmpBuilder) Ge

func (c CmpBuilder) Ge(r Operand, opts ...Option) Builder

Ge is "greater than or equal".

func (CmpBuilder) Gt

func (c CmpBuilder) Gt(r Operand, opts ...Option) Builder

Gt is "greater than".

func (CmpBuilder) Le

func (c CmpBuilder) Le(r Operand, opts ...Option) Builder

Le is "less than or equal".

func (CmpBuilder) Lt

func (c CmpBuilder) Lt(r Operand, opts ...Option) Builder

Lt, Le, Gt, Ge, Eq and Ne finish a compare rule.

func (CmpBuilder) Ne

func (c CmpBuilder) Ne(r Operand, opts ...Option) Builder

Ne is "not equal".

type Cond

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

Cond is a condition under construction.

func Absent

func Absent(field string) Cond

Absent is true when the field is blank.

func AllOf

func AllOf(cs ...Cond) Cond

AllOf is true when every condition is.

func AnyOf

func AnyOf(cs ...Cond) Cond

AnyOf is true when at least one condition is.

func Eq

func Eq(field string, value any) Cond

Eq is true when the field strictly equals value.

func In

func In(field string, values ...any) Cond

In is true when the field equals one of values.

func Ne

func Ne(field string, value any) Cond

Ne is true when Eq would be false.

func Not

func Not(c Cond) Cond

Not negates a condition.

func Present

func Present(field string) Cond

Present is true when the field is not blank.

type Condition

type Condition struct {
	Eq      *FieldValue  `json:"eq,omitempty"`
	Ne      *FieldValue  `json:"ne,omitempty"`
	In      *FieldValues `json:"in,omitempty"`
	Present *FieldRef    `json:"present,omitempty"`
	Absent  *FieldRef    `json:"absent,omitempty"`
	All     []Condition  `json:"all,omitempty"`
	Any     []Condition  `json:"any,omitempty"`
	Not     *Condition   `json:"not,omitempty"`
}

Condition is a condition tree; exactly one member is set.

type FieldRef

type FieldRef struct {
	Field string `json:"field"`
}

FieldRef names one field.

type FieldValue

type FieldValue struct {
	Field string `json:"field"`
	Value any    `json:"value"`
}

FieldValue is the {field, value} pair used by eq, ne and in conditions.

type FieldValues

type FieldValues struct {
	Field  string `json:"field"`
	Values []any  `json:"values"`
}

FieldValues is the {field, values} pair used by "in".

type Issue

type Issue struct {
	Path   []string       `json:"path"`
	RuleID string         `json:"ruleId"`
	Key    string         `json:"key"`
	Params map[string]any `json:"params"`
}

Issue is one failing rule, in the shape every implementation shares.

func Evaluate

func Evaluate(rules []Rule, data map[string]any, side Side) []Issue

Evaluate runs rules against data, the wire form of the object (a decoded JSON object), and returns one issue per failing rule, in rule order. The result is never nil. Rules should have passed ValidateRules; a rule of an unknown kind is ignored here.

type Kind

type Kind string

Kind names a rule kind.

const (
	KindRequiredWhen Kind = "required_when"
	KindCompare      Kind = "compare"
	KindAtLeastOneOf Kind = "at_least_one_of"
	KindExactlyOneOf Kind = "exactly_one_of"
	KindAllOrNone    Kind = "all_or_none"
)

The five rule kinds of format v1.

type Message

type Message struct {
	Key    string         `json:"key"`
	Params map[string]any `json:"params,omitempty"`
}

Message is the text key (and optional params) a failing rule reports.

type Operand

type Operand struct {
	Field    string
	Value    any
	HasValue bool
}

Operand is one side of a compare: a field reference or a constant.

func Ref

func Ref(field string) Operand

Ref compares against another field.

func Val

func Val(v any) Operand

Val compares against a constant (string, number or boolean).

func (Operand) MarshalJSON

func (o Operand) MarshalJSON() ([]byte, error)

MarshalJSON writes {"field": ...} or {"value": ...}.

func (*Operand) UnmarshalJSON

func (o *Operand) UnmarshalJSON(b []byte) error

UnmarshalJSON reads {"field": ...} or {"value": ...}.

type Option

type Option func(*draft)

Option customises a rule.

func As

func As(t string) Option

As sets the compare type ("number", "string", "date" or "datetime") when it cannot be inferred from the Go field type.

func ID

func ID(id string) Option

ID sets the rule id; the default is TypeName.kind.field.

func Key

func Key(key string) Option

Key sets the message key (required, e.g. "rules.company_required").

func Params

func Params(p map[string]any) Option

Params sets the message params (strings, numbers, booleans or nil).

func Path

func Path(p string) Option

Path sets the field the issue is reported on.

func ServerOnly

func ServerOnly() Option

ServerOnly makes clients skip the rule.

type Problem

type Problem struct {
	Type      string  `json:"type"`
	Title     string  `json:"title"`
	Status    int     `json:"status"`
	Detail    string  `json:"detail,omitempty"`
	Validonce []Issue `json:"validonce"`
}

Problem is the RFC 9457 problem details body validonce servers return when rules fail: the issue list sits in a top-level member named "validonce" (see "Transport" in rule-format-v1). It is also an error, so a handler can return it directly.

func NewProblem

func NewProblem(issues []Issue, status int) *Problem

NewProblem builds the problem for issues with the given status (0 means 422).

func (*Problem) ContentType

func (p *Problem) ContentType(ct string) string

ContentType maps a JSON content type to application/problem+json, as problem details require.

func (*Problem) Error

func (p *Problem) Error() string

Error implements error.

func (*Problem) GetStatus

func (p *Problem) GetStatus() int

GetStatus returns the HTTP status (the method web frameworks look for).

type Rule

type Rule struct {
	ID         string     `json:"id"`
	Kind       Kind       `json:"kind"`
	Path       string     `json:"path,omitempty"`
	Field      string     `json:"field,omitempty"`
	When       *Condition `json:"when,omitempty"`
	Left       *Operand   `json:"left,omitempty"`
	Op         string     `json:"op,omitempty"`
	Right      *Operand   `json:"right,omitempty"`
	Type       string     `json:"type,omitempty"`
	Fields     []string   `json:"fields,omitempty"`
	Message    Message    `json:"message"`
	ServerOnly bool       `json:"server_only,omitempty"`
}

Rule is one rule of any kind. Only the members of its kind are used.

type RuleSet

type RuleSet struct {
	Version int    `json:"version"`
	Rules   []Rule `json:"rules"`
}

RuleSet is the value of "x-validonce".

func ParseRuleSet

func ParseRuleSet(data []byte) (RuleSet, error)

ParseRuleSet decodes and validates a rule set. Unknown versions, kinds and malformed rules are rejected, never skipped.

func (RuleSet) Hash added in v0.6.0

func (rs RuleSet) Hash() (string, error)

Hash returns the identity of the rule set as it marshals to JSON, which is the form exporters publish.

func (RuleSet) Validate

func (rs RuleSet) Validate() error

Validate checks the rule set against the structure rule format v1 requires.

type Rules

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

Rules is a validated rule set bound to one Go struct type. Field names in the rules are the JSON names of the struct's fields (its `json` tags), the wire names the format uses.

func Build

func Build[T any](builders ...Builder) (*Rules, error)

Build turns builders into a validated Rules for struct type T. It checks, by reflection, that every field a rule names is a JSON field of T, that compare types are supported and match the Go field types, and that rule ids are unique. Call it once at startup; every problem is reported together.

func MustBuild

func MustBuild[T any](builders ...Builder) *Rules

MustBuild is Build that panics, for package-level variables.

func (*Rules) Check

func (r *Rules) Check(v any) ([]Issue, error)

Check marshals v to its wire form with encoding/json and evaluates the rules on the server side.

func (*Rules) CheckSide

func (r *Rules) CheckSide(v any, side Side) ([]Issue, error)

CheckSide is Check for a chosen side.

func (*Rules) Evaluate

func (r *Rules) Evaluate(data map[string]any, side Side) []Issue

Evaluate runs the rules on the wire form of an object (a decoded JSON map).

func (*Rules) Model

func (r *Rules) Model() string

Model returns the struct's type name, the prefix of default rule ids.

func (*Rules) Problem

func (r *Rules) Problem(v any) error

Problem evaluates r on v (server side) and returns a *Problem when any rule fails, else nil. A value that cannot be encoded is returned as an ordinary error.

func (*Rules) Rule

func (r *Rules) Rule(id string) (Rule, bool)

Rule returns the rule with the given id.

func (*Rules) Set

func (r *Rules) Set() RuleSet

Set returns the rules as data, ready to be written under "x-validonce".

type RulesCheck added in v0.6.0

type RulesCheck struct {
	Outcome   RulesOutcome
	Current   string
	Submitted []string
}

RulesCheck is the result of CheckRules.

func CheckRules added in v0.6.0

func CheckRules(header, current string, accept []AcceptHash, now time.Time) RulesCheck

CheckRules decides whether a request's rules are current. header is the Validonce-Rules value ("" when missing) and current the server's hash.

type RulesMode added in v0.6.0

type RulesMode string

RulesMode says how a server treats the Validonce-Rules header.

const (
	RulesOff     RulesMode = "off"
	RulesReport  RulesMode = "report"
	RulesEnforce RulesMode = "enforce"
)

The modes: no check (default), flag stale requests, or reject them with 412.

type RulesOutcome added in v0.6.0

type RulesOutcome string

RulesOutcome is the decision for one request.

const (
	RulesAbsent  RulesOutcome = "absent"
	RulesCurrent RulesOutcome = "current"
	RulesStale   RulesOutcome = "stale"
)

Absent: no usable header. Current: a submitted hash is current or accepted. Stale: none is.

type Side

type Side int

Side selects which rules run: the server runs every rule, a client skips server_only rules.

const (
	Server Side = iota
	Client
)

The two sides.

type StaleRulesDetails added in v0.6.0

type StaleRulesDetails struct {
	Current   string   `json:"current"`
	Submitted []string `json:"submitted"`
}

StaleRulesDetails is the validonce member of the 412 body.

type StaleRulesProblem added in v0.6.0

type StaleRulesProblem struct {
	Type      string            `json:"type"`
	Title     string            `json:"title"`
	Status    int               `json:"status"`
	Validonce StaleRulesDetails `json:"validonce"`
	Rules     *RuleSet          `json:"rules,omitempty"`
	OpenAPI   string            `json:"openapi,omitempty"`
}

StaleRulesProblem is the 412 body (application/problem+json) for a stale request in enforce mode.

func NewStaleRulesProblem added in v0.6.0

func NewStaleRulesProblem(check RulesCheck) StaleRulesProblem

NewStaleRulesProblem builds the 412 body for a check.

type WhenBuilder

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

WhenBuilder is the first half of a required_when rule.

func When

func When(c Cond) WhenBuilder

When starts a required_when rule.

func (WhenBuilder) Require

func (w WhenBuilder) Require(field string, opts ...Option) Builder

Require finishes it: field must not be blank when the condition holds.

Directories

Path Synopsis
Package humaonce connects validonce rules to Huma (github.com/danielgtaylor/huma/v2): it adds x-validonce to a type's OpenAPI component schema and turns failing rules into a 422 RFC 9457 problem details response with a top-level "validonce" member.
Package humaonce connects validonce rules to Huma (github.com/danielgtaylor/huma/v2): it adds x-validonce to a type's OpenAPI component schema and turns failing rules into a 422 RFC 9457 problem details response with a top-level "validonce" member.
Package playground runs validonce rules inside go-playground/validator, so they execute with the validation an application already has (validate.Struct, Echo, Gin, ...).
Package playground runs validonce rules inside go-playground/validator, so they execute with the validation an application already has (validate.Struct, Echo, Gin, ...).

Jump to

Keyboard shortcuts

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