validation

package
v1.167.0 Latest Latest
Warning

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

Go to latest
Published: Jul 23, 2026 License: Apache-2.0 Imports: 21 Imported by: 0

Documentation

Overview

Package validation provides validation helpers built on top of ozzo-validation.

The package contains two complementary layers:

  • general-purpose Go validation helpers that extend ozzo-validation and its `is` package
  • schema-oriented helpers whose naming and behaviour align with external schema ecosystems where that maps cleanly to runtime validation rules

In particular, the schema-oriented helpers aim to cover practical rule vocabulary commonly found in:

  • JSON Schema
  • OpenAPI / Kubernetes CRD schema extensions
  • Protovalidate and protobuf validation rule sets
  • XSD-style structural constraints
  • Avro- and Thrift-style data shape constraints where they make sense in a runtime Go validation package

The package does not try to replace full schema compilers. Instead, it provides reusable validation rules that are convenient when callers already have decoded Go values and want rule-level validation with ozzo semantics.

Upstream projects:

Documentation:

logical.go contains logical validation combinators.

These helpers combine other validation rules into larger rule expressions such as “any of these must pass”, “exactly one must pass”, or “if rule A passes, rule B must also pass”. They complement ozzo-validation's default behaviour, which normally applies multiple rules with AND semantics.

Index

Constants

This section is empty.

Variables

IsBase64 validates whether a value is a base64 encoded string. It is similar to is.Base64 but more generic and robust although less performant.

View Source
var IsDuration = validation.NewStringRule(func(value string) bool {
	_, err := time.ParseDuration(value)
	return err == nil
}, errInvalidDurationDescription)

IsDuration validates whether a string or byte slice is a valid Go duration.

View Source
var IsPathParameter = urlutils.IsPathParameter

IsPathParameter validates OpenAPI-style path parameter segments such as `{id}`.

View Source
var IsPort = validation.By(isPort)

IsPort validates whether a value is a port using is.Port from github.com/go-ozzo/ozzo-validation/v4. However, it supports all base go integer types not just strings.

View Source
var IsRFC3339Timestamp = validation.NewStringRule(func(value string) bool {
	if _, err := time.Parse(time.RFC3339, value); err == nil {
		return true
	}
	if _, err := time.Parse(time.RFC3339Nano, value); err == nil {
		return true
	}
	return false
}, errInvalidTimestampDescription)

IsRFC3339Timestamp validates whether a string or byte slice is a valid RFC3339 timestamp.

View Source
var IsURI = urlutils.IsURI

IsURI validates URI strings and byte slices.

Functions

func AdditionalItemKeys added in v1.167.0

func AdditionalItemKeys[T any, K comparable](keyFunc collection.KeyFunc[T, K], keys ...K) validation.Rule

AdditionalItemKeys validates that a collection contains no item whose derived key lies outside the supplied key set.

Example: `AdditionalItemKeys(func(value user) string { return value.Role }, "admin", "editor")` rejects `[]user{{Role: "viewer"}}`.

func AdditionalItems added in v1.167.0

func AdditionalItems[T any, K comparable](keyFunc collection.KeyFunc[T, K], items ...T) validation.Rule

AdditionalItems validates that a collection contains no item whose derived key lies outside the supplied reference item set.

Example: `AdditionalItems(func(value string) string { return value }, "a", "b")` rejects `[]string{"c"}`.

func AdditionalProperties added in v1.167.0

func AdditionalProperties(keys ...string) validation.Rule

AdditionalProperties validates that a map or struct contains no property name outside the supplied known set.

This is a simplified helper corresponding to the JSON Schema `additionalProperties: false` pattern.

Example: `AdditionalProperties("a", "b")` rejects `map[string]any{"c": 1}`.

Reference: https://json-schema.org/understanding-json-schema/reference/object#additional-properties

func AdditionalPropertiesBy added in v1.167.0

func AdditionalPropertiesBy(keys ...any) validation.Rule

AdditionalPropertiesBy resolves strings, `[]string`, or field references against the validated value and applies AdditionalProperties using the resulting names.

Example:

cfg := &Config{}
err := validation.Validate(cfg, AdditionalPropertiesBy(&cfg.Name, &cfg.Enabled, &cfg.Mode))

func AllOf added in v1.167.0

func AllOf(rules ...validation.Rule) validation.Rule

AllOf returns a rule that succeeds only if all nested rules succeed.

This is a schema-oriented alias for NewAllRule. Example: `AllOf(validation.Required, is.Email)` requires a non-empty email.

Reference: https://json-schema.org/understanding-json-schema/reference/combining#allof

func AnyOf added in v1.167.0

func AnyOf(rules ...validation.Rule) validation.Rule

AnyOf returns a rule that succeeds if at least one nested rule succeeds.

This is a schema-oriented alias for NewAnyRule. Example: `AnyOf(is.Email, is.UUID)` accepts `"user@example.com"`.

Reference: https://json-schema.org/understanding-json-schema/reference/combining#anyof

func ArrayItems added in v1.167.0

func ArrayItems(rule validation.Rule) validation.Rule

ArrayItems validates that every item in an array or slice satisfies rule.

Example: `ArrayItems(Type("string"))` accepts `[]any{"a", "b"}`.

func AtLeast added in v1.167.0

func AtLeast(min int, rule ...validation.Rule) validation.Rule

AtLeast returns a rule that succeeds if at least min of the provided rules succeed.

func AtLeastOneItem added in v1.167.0

func AtLeastOneItem[T any, K comparable](keyFunc collection.KeyFunc[T, K], items ...T) validation.Rule

AtLeastOneItem validates that a collection contains an item matching at least one of the supplied reference items.

Example: `AtLeastOneItem(func(value string) string { return value }, "a", "b")` rejects `[]string{}`.

func AtLeastOneItemKey added in v1.167.0

func AtLeastOneItemKey[T any, K comparable](keyFunc collection.KeyFunc[T, K], keys ...K) validation.Rule

AtLeastOneItemKey validates that a collection contains an item matching at least one of the supplied keys.

Example: `AtLeastOneItemKey(func(value user) string { return value.Role }, "admin", "editor")` rejects `[]user{}`.

func AtLeastOneProperty added in v1.167.0

func AtLeastOneProperty(keys ...string) validation.Rule

AtLeastOneProperty validates that at least one of the named keys or fields is set in a map or struct value.

Example: `AtLeastOneProperty("A", "B")` rejects a value where neither `A` nor `B` is set.

This is not a direct JSON Schema keyword, but is useful for OpenAPI-like object validation.

OpenAPI reference: https://spec.openapis.org/oas/latest.html#schema-object

func AtLeastOnePropertyBy added in v1.167.0

func AtLeastOnePropertyBy(keys ...any) validation.Rule

AtLeastOnePropertyBy resolves strings, `[]string`, or field references against the validated value and applies AtLeastOneProperty.

Example:

cfg := &Config{}
err := validation.Validate(cfg, AtLeastOnePropertyBy(&cfg.Token, &cfg.Username, &cfg.APIKey))

func AtLeastWithContext added in v1.167.0

func AtLeastWithContext(min int, rule ...validation.RuleWithContext) validation.RuleWithContext

AtLeastWithContext returns a context-aware rule that succeeds if at least min of the provided context-aware rules succeed.

func AtMost added in v1.167.0

func AtMost(max int, rule ...validation.Rule) validation.Rule

AtMost returns a rule that succeeds if no more than max of the provided rules succeed.

func AtMostOneItem added in v1.167.0

func AtMostOneItem[T any, K comparable](keyFunc collection.KeyFunc[T, K], items ...T) validation.Rule

AtMostOneItem validates that a collection contains items matching no more than one of the supplied reference items.

Example: `AtMostOneItem(func(value string) string { return value }, "a", "b")` rejects `[]string{"a", "b"}`.

func AtMostOneItemKey added in v1.167.0

func AtMostOneItemKey[T any, K comparable](keyFunc collection.KeyFunc[T, K], keys ...K) validation.Rule

AtMostOneItemKey validates that a collection contains items matching no more than one of the supplied keys.

Example: `AtMostOneItemKey(func(value user) string { return value.Role }, "admin", "editor")` rejects `[]user{{Role: "admin"}, {Role: "editor"}}`.

func AtMostOneProperty added in v1.167.0

func AtMostOneProperty(keys ...string) validation.Rule

AtMostOneProperty validates that no more than one of the named keys or fields is set in a map or struct value.

Example: `AtMostOneProperty("A", "B")` rejects a value where both `A` and `B` are non-empty.

This is not a direct JSON Schema keyword, but is useful for OpenAPI-like object validation.

OpenAPI reference: https://spec.openapis.org/oas/latest.html#schema-object

func AtMostOnePropertyBy added in v1.167.0

func AtMostOnePropertyBy(keys ...any) validation.Rule

AtMostOnePropertyBy resolves strings, `[]string`, or field references against the validated value and applies AtMostOneProperty.

Example:

cfg := &Config{}
err := validation.Validate(cfg, AtMostOnePropertyBy(&cfg.Token, &cfg.Username, &cfg.APIKey))

func AtMostWithContext added in v1.167.0

func AtMostWithContext(max int, rule ...validation.RuleWithContext) validation.RuleWithContext

AtMostWithContext returns a context-aware rule that succeeds if no more than max of the provided context-aware rules succeed.

func Const added in v1.167.0

func Const(expected any) validation.Rule

Const validates that a value is exactly equal to expected.

This uses the same equality semantics as Enum, including numeric equality across compatible JSON-style number representations. This is useful for schema-style validations where one field must have a fixed discriminator or version value. Example: `Const("v1")` accepts `"v1"` and rejects `"v2"`.

Reference: https://json-schema.org/understanding-json-schema/reference/const

func Contains added in v1.167.0

func Contains(rule validation.Rule) validation.Rule

Contains validates the JSON Schema `contains` constraint.

The rule succeeds when at least one item in the array or slice satisfies rule. Example: `Contains(Const("a"))` accepts `[]string{"a", "b"}`.

Reference: https://json-schema.org/understanding-json-schema/reference/array#contains

func ContainsString added in v1.167.0

func ContainsString(substring string) validation.Rule

ContainsString validates that a string or byte slice contains substring.

func DependentRequired added in v1.167.0

func DependentRequired(dependencies map[string][]string) validation.Rule

DependentRequired validates the JSON Schema `dependentRequired` constraint.

For each trigger property key in dependencies, if that property is present, all listed dependent properties must also be present.

Example: `DependentRequired(map[string][]string{"a": {"b"}})` rejects `map[string]any{"a": 1}`.

Reference: https://json-schema.org/understanding-json-schema/reference/conditionals#dependentrequired

func DependentRequiredBy added in v1.167.0

func DependentRequiredBy(dependencies map[any]any) validation.Rule

DependentRequiredBy resolves dependency trigger keys from strings or field references and dependent properties from strings, `[]string`, or field references before applying DependentRequired.

Example:

cfg := &Config{}
err := validation.Validate(cfg, DependentRequiredBy(map[any]any{&cfg.Username: []any{&cfg.Password, &cfg.Scheme}}))

func DependentRequiredItemKeys added in v1.167.0

func DependentRequiredItemKeys[T any, K comparable](keyFunc collection.KeyFunc[T, K], dependencies map[K][]K) validation.Rule

DependentRequiredItemKeys validates that if a collection contains an item for a trigger key then it also contains items for each dependent key.

Example: `DependentRequiredItemKeys(func(value user) string { return value.Role }, map[string][]string{"admin": {"editor"}})` rejects `[]user{{Role: "admin"}}`.

func DependentRequiredItems added in v1.167.0

func DependentRequiredItems[T comparable, K comparable](keyFunc collection.KeyFunc[T, K], dependencies map[T][]T) validation.Rule

DependentRequiredItems validates that if a collection contains an item matching a trigger item then it also contains items matching each dependent item.

Example: `DependentRequiredItems(func(value string) string { return value }, map[string][]string{"a": {"b"}})` rejects `[]string{"a"}`.

func DependentSchemas added in v1.167.0

func DependentSchemas(dependencies map[string]validation.Rule) validation.Rule

DependentSchemas validates the JSON Schema `dependentSchemas` constraint.

For each trigger property key in dependencies, if that property is present, the corresponding rule is applied to the whole object.

Example: `DependentSchemas(map[string]validation.Rule{"a": RequiredProperties("b")})` rejects `map[string]any{"a": 1}`.

Reference: https://json-schema.org/understanding-json-schema/reference/conditionals#dependentschemas

func DependentSchemasBy added in v1.167.0

func DependentSchemasBy(dependencies map[any]validation.Rule) validation.Rule

DependentSchemasBy resolves dependency trigger properties from strings or field references before applying DependentSchemas.

Example:

cfg := &Config{}
err := validation.Validate(cfg, DependentSchemasBy(map[any]validation.Rule{&cfg.Username: RequiredPropertiesBy(&cfg.Password)}))

func DurationConst added in v1.167.0

func DurationConst(expected time.Duration) validation.Rule

DurationConst validates that a duration value is exactly equal to expected.

func DurationExclusiveMaximum added in v1.167.0

func DurationExclusiveMaximum(max time.Duration) validation.Rule

DurationExclusiveMaximum validates that a duration value is strictly less than max.

func DurationExclusiveMinimum added in v1.167.0

func DurationExclusiveMinimum(min time.Duration) validation.Rule

DurationExclusiveMinimum validates that a duration value is strictly greater than min.

func DurationMaximum added in v1.167.0

func DurationMaximum(max time.Duration) validation.Rule

DurationMaximum validates that a duration value is less than or equal to max.

func DurationMinimum added in v1.167.0

func DurationMinimum(min time.Duration) validation.Rule

DurationMinimum validates that a duration value is greater than or equal to min.

func Enum added in v1.167.0

func Enum(values ...any) validation.Rule

Enum validates that a value is one of a fixed set of allowed values.

Unlike ozzo's `validation.In(...)`, this helper does not treat empty values as automatically valid. It follows JSON Schema `enum` semantics instead. Example: `Enum("red", "blue")` accepts `"blue"` and rejects `"green"`.

Reference: https://json-schema.org/understanding-json-schema/reference/enum

func Exactly added in v1.167.0

func Exactly(n int, rule ...validation.Rule) validation.Rule

Exactly returns a rule that succeeds if exactly `n` of the provided rules succeed.

func ExactlyWithContext added in v1.167.0

func ExactlyWithContext(n int, rule ...validation.RuleWithContext) validation.RuleWithContext

ExactlyWithContext returns a context-aware rule that succeeds if exactly `n` of the provided context-aware rules succeed.

func ExclusiveMaximum added in v1.167.0

func ExclusiveMaximum(max any) validation.Rule

ExclusiveMaximum validates the JSON Schema `exclusive_maximum` constraint.

Example: `ExclusiveMaximum(10)` accepts `9` and rejects `10`.

Reference: https://json-schema.org/understanding-json-schema/reference/numeric#range

func ExclusiveMinimum added in v1.167.0

func ExclusiveMinimum(min any) validation.Rule

ExclusiveMinimum validates the JSON Schema `exclusive_minimum` constraint.

Example: `ExclusiveMinimum(10)` accepts `11` and rejects `10`.

Reference: https://json-schema.org/understanding-json-schema/reference/numeric#range

func ForbiddenItemKeys added in v1.167.0

func ForbiddenItemKeys[T any, K comparable](keyFunc collection.KeyFunc[T, K], keys ...K) validation.Rule

ForbiddenItemKeys validates that a collection contains no items matching any of the supplied keys.

Example: `ForbiddenItemKeys(func(value user) string { return value.Role }, "debug")` rejects `[]user{{Role: "debug"}}`.

func ForbiddenItems added in v1.167.0

func ForbiddenItems[T any, K comparable](keyFunc collection.KeyFunc[T, K], items ...T) validation.Rule

ForbiddenItems validates that a collection contains no items matching any of the supplied reference items.

Example: `ForbiddenItems(func(value string) string { return value }, "debug")` rejects `[]string{"debug"}`.

func ForbiddenProperties added in v1.167.0

func ForbiddenProperties(keys ...string) validation.Rule

ForbiddenProperties validates that none of the named keys or fields is set in a map or struct value.

Example: `ForbiddenProperties("debug")` rejects `{"debug": true}`.

This is not a direct JSON Schema keyword, but is useful for OpenAPI-like object validation.

OpenAPI reference: https://spec.openapis.org/oas/latest.html#schema-object

func ForbiddenPropertiesBy added in v1.167.0

func ForbiddenPropertiesBy(keys ...any) validation.Rule

ForbiddenPropertiesBy resolves strings, `[]string`, or field references against the validated value and applies ForbiddenProperties.

Example:

cfg := &Config{}
err := validation.Validate(cfg, ForbiddenPropertiesBy(&cfg.Debug, &cfg.InternalOnly))

func IfThenElse added in v1.167.0

func IfThenElse(ifRule, thenRule, elseRule validation.Rule) validation.Rule

IfThenElse returns a rule that evaluates ifRule first and then selects which branch rule to apply.

If ifRule succeeds, thenRule is applied. Otherwise elseRule is applied. A nil branch is treated as a no-op branch that succeeds.

func IfThenElseWithContext added in v1.167.0

func IfThenElseWithContext(ifRule, thenRule, elseRule validation.RuleWithContext) validation.RuleWithContext

IfThenElseWithContext returns a context-aware conditional rule.

If ifRule succeeds, thenRule is applied. Otherwise elseRule is applied. A nil branch is treated as a no-op branch that succeeds.

func Implies added in v1.167.0

func Implies(antecedent, consequent validation.Rule) validation.Rule

Implies returns a rule that succeeds when antecedent fails, or when both the antecedent and consequent rules succeed.

This is the logical implication combinator: `antecedent -> consequent`.

func ImpliesWithContext added in v1.167.0

func ImpliesWithContext(antecedent, consequent validation.RuleWithContext) validation.RuleWithContext

ImpliesWithContext returns a context-aware implication rule.

It succeeds when antecedent fails, or when both the antecedent and consequent rules succeed.

func LengthExact added in v1.167.0

func LengthExact(n int) validation.Rule

LengthExact validates that a length-aware value has exactly n elements.

func LengthRule added in v1.167.0

func LengthRule(min, max *int) validation.Rule

LengthRule returns an ozzo length rule with optional minimum and maximum bounds.

A nil minimum means zero. A nil maximum means unbounded.

Strings are treated as a special case and validated using rune length rather than byte length so the behaviour is closer to JSON Schema string length semantics. Other length-aware values use ozzo's standard Length rule.

Example: `LengthRule(field.ToOptionalInt(1), field.ToOptionalInt(3))` accepts strings, slices, arrays, and maps whose length is between one and three inclusive.

References:

func Like added in v1.167.0

func Like(re *regexp.Regexp) validation.Rule

Like validates that a string or byte slice matches re.

func MapKeys added in v1.167.0

func MapKeys(rule validation.Rule) validation.Rule

MapKeys validates that every key in a map satisfies rule.

It also accepts `iter.Seq2[string, any]`-style inputs and validates each yielded key.

Example: `MapKeys(Pattern(regexp.MustCompile("^[a-z]+$")))` accepts `map[string]any{"alpha": 1}`.

func MapValues added in v1.167.0

func MapValues(rule validation.Rule) validation.Rule

MapValues validates that every value in a map satisfies rule.

It also accepts `iter.Seq2[string, any]`-style inputs and validates each yielded value.

Example: `MapValues(Type("string"))` accepts `map[string]any{"a": "x"}`.

func MaxContains added in v1.167.0

func MaxContains(max int, rule validation.Rule) validation.Rule

MaxContains validates the JSON Schema `maxContains` constraint.

The rule succeeds when at most max items in the array or slice satisfy rule. Example: `MaxContains(1, Const("a"))` rejects `[]string{"a", "a"}`.

Reference: https://json-schema.org/understanding-json-schema/reference/array#contains

func MaxItems added in v1.167.0

func MaxItems(max int) validation.Rule

MaxItems validates the JSON Schema `max_items` constraint.

Example: `MaxItems(2)` accepts `[1,2]` and rejects `[1,2,3]`.

Reference: https://json-schema.org/understanding-json-schema/reference/array#length

func MaxLength added in v1.167.0

func MaxLength(max int) validation.Rule

MaxLength validates the JSON Schema `max_length` constraint.

This counts Unicode code points rather than bytes. Example: `MaxLength(5)` accepts `hello` and rejects `hello!`.

Reference: https://json-schema.org/understanding-json-schema/reference/string#length

func MaxOccurs added in v1.167.0

func MaxOccurs(substring string, max int) validation.Rule

MaxOccurs validates that substring occurs at most max times in a string or byte slice.

func MaxProperties added in v1.167.0

func MaxProperties(max int) validation.Rule

MaxProperties validates the JSON Schema `max_properties` constraint.

Example: `MaxProperties(2)` accepts a map with two keys and rejects one with three.

Reference: https://json-schema.org/understanding-json-schema/reference/object#size

func Maximum added in v1.167.0

func Maximum(max any) validation.Rule

Maximum validates the JSON Schema `maximum` constraint.

Example: `Maximum(10)` accepts `10` and rejects `11`.

Reference: https://json-schema.org/understanding-json-schema/reference/numeric#range

func MinContains added in v1.167.0

func MinContains(min int, rule validation.Rule) validation.Rule

MinContains validates the JSON Schema `minContains` constraint.

The rule succeeds when at least min items in the array or slice satisfy rule. Example: `MinContains(2, Const("a"))` accepts `[]string{"a", "b", "a"}`.

Reference: https://json-schema.org/understanding-json-schema/reference/array#contains

func MinItems added in v1.167.0

func MinItems(min int) validation.Rule

MinItems validates the JSON Schema `min_items` constraint.

Example: `MinItems(2)` accepts `[1,2]` and rejects `[1]`.

Reference: https://json-schema.org/understanding-json-schema/reference/array#length

func MinLength added in v1.167.0

func MinLength(min int) validation.Rule

MinLength validates the JSON Schema `min_length` constraint.

This counts Unicode code points rather than bytes. Example: `MinLength(5)` accepts `hello` and rejects `hell`.

Reference: https://json-schema.org/understanding-json-schema/reference/string#length

func MinOccurs added in v1.167.0

func MinOccurs(substring string, min int) validation.Rule

MinOccurs validates that substring occurs at least min times in a string or byte slice.

func MinProperties added in v1.167.0

func MinProperties(min int) validation.Rule

MinProperties validates the JSON Schema `min_properties` constraint.

Example: `MinProperties(2)` accepts a map with two keys and rejects one with one.

Reference: https://json-schema.org/understanding-json-schema/reference/object#size

func Minimum added in v1.167.0

func Minimum(min any) validation.Rule

Minimum validates the JSON Schema `minimum` constraint.

Example: `Minimum(10)` accepts `10` and rejects `9`.

Reference: https://json-schema.org/understanding-json-schema/reference/numeric#range

func MultipleOf added in v1.167.0

func MultipleOf(base any) validation.Rule

MultipleOf validates the JSON Schema `multiple_of` constraint.

Example: `MultipleOf(5)` accepts `10` and rejects `11`.

Reference: https://json-schema.org/understanding-json-schema/reference/numeric#multiples

func MutuallyExclusiveItemKeys added in v1.167.0

func MutuallyExclusiveItemKeys[T any, K comparable](keyFunc collection.KeyFunc[T, K], keys ...K) validation.Rule

MutuallyExclusiveItemKeys validates that a collection contains items matching at most one of the supplied keys.

Example: `MutuallyExclusiveItemKeys(func(value user) string { return value.Role }, "admin", "editor")` rejects `[]user{{Role: "admin"}, {Role: "editor"}}`.

func MutuallyExclusiveItems added in v1.167.0

func MutuallyExclusiveItems[T any, K comparable](keyFunc collection.KeyFunc[T, K], items ...T) validation.Rule

MutuallyExclusiveItems validates that a collection contains items matching at most one of the supplied reference items.

Example: `MutuallyExclusiveItems(func(value string) string { return value }, "a", "b")` rejects `[]string{"a", "b"}`.

func MutuallyExclusiveWith added in v1.167.0

func MutuallyExclusiveWith(keys ...string) validation.Rule

MutuallyExclusiveWith validates that at most one of the named keys or fields is set in a map or struct value.

This helper is inspired by non-standard schema-style object constraints and is useful when several alternative fields are allowed but must not appear together. It is not a direct JSON Schema keyword, but it is often useful for OpenAPI-style request and configuration validation.

OpenAPI reference: https://spec.openapis.org/oas/latest.html#schema-object

Example: `MutuallyExclusiveWith("A", "B")` rejects a value where both `A` and `B` are non-empty.

func MutuallyExclusiveWithBy added in v1.167.0

func MutuallyExclusiveWithBy(keys ...any) validation.Rule

MutuallyExclusiveWithBy resolves strings, `[]string`, or field references against the validated value and applies MutuallyExclusiveWith using the resulting property names.

Example:

cfg := &Config{}
err := validation.Validate(cfg, MutuallyExclusiveWithBy(&cfg.Token, &cfg.Username, &cfg.APIKey))

func NOf added in v1.167.0

func NOf(n int, rule ...validation.Rule) validation.Rule

NOf returns a rule that succeeds only if exactly `n` of the provided rules succeed.

In other words, this is an “N of these rules must pass” combinator.

Example: `NOf(1, is.Email, is.UUID)` accepts a valid email or a valid UUID, but rejects values that satisfy neither rule and values that satisfy more than one rule.

References:

It is a readability-oriented alias for Exactly.

func NOfWithContext added in v1.167.0

func NOfWithContext(n int, rule ...validation.RuleWithContext) validation.RuleWithContext

NOfWithContext returns a context-aware rule that succeeds only if exactly `n` of the provided context-aware rules succeed.

In other words, this is the context-aware form of “N of these rules must pass”.

Example: `NOfWithContext(1, emailRule, uuidRule)` accepts a value only when exactly one of the supplied contextual rules succeeds.

References:

It is a readability-oriented alias for ExactlyWithContext.

func NewAllRule added in v1.153.0

func NewAllRule(rule ...validation.Rule) validation.Rule

NewAllRule returns a rule that succeeds only if all of the provided rules succeed.

This is equivalent to grouping the same rules under validation.Validate.

func NewAllRuleWithContext added in v1.153.0

func NewAllRuleWithContext(rule ...validation.RuleWithContext) validation.RuleWithContext

NewAllRuleWithContext returns a context-aware rule that succeeds only if all of the provided context-aware rules succeed.

This is equivalent to grouping the same rules under validation.ValidateWithContext.

func NewAnyRule added in v1.153.0

func NewAnyRule(rule ...validation.Rule) validation.Rule

NewAnyRule returns a rule that succeeds if at least one of the provided rules succeeds.

This complements validation.Validate, where multiple rules are normally combined with AND semantics.

func NewAnyRuleWithContext added in v1.153.0

func NewAnyRuleWithContext(rule ...validation.RuleWithContext) validation.RuleWithContext

NewAnyRuleWithContext returns a context-aware rule that succeeds if at least one of the provided context-aware rules succeeds.

This complements validation.Validate and validation.ValidateWithContext, where multiple rules are normally combined with AND semantics.

func NewNoneRule added in v1.153.0

func NewNoneRule(rule ...validation.Rule) validation.Rule

NewNoneRule returns a rule that succeeds only if none of the provided rules succeed.

This is useful when a value must not match any rule in a given set.

func NewNoneRuleWithContext added in v1.153.0

func NewNoneRuleWithContext(rule ...validation.RuleWithContext) validation.RuleWithContext

NewNoneRuleWithContext returns a context-aware rule that succeeds only if none of the provided context-aware rules succeed.

func NewOneOfRule added in v1.167.0

func NewOneOfRule(rule ...validation.Rule) validation.Rule

NewOneOfRule returns a rule that succeeds only if exactly one of the provided rules succeeds.

func NewOneOfRuleWithContext added in v1.167.0

func NewOneOfRuleWithContext(rule ...validation.RuleWithContext) validation.RuleWithContext

NewOneOfRuleWithContext returns a context-aware rule that succeeds only if exactly one of the provided context-aware rules succeeds.

func NoneOf added in v1.167.0

func NoneOf(rules ...validation.Rule) validation.Rule

NoneOf returns a rule that succeeds only if none of the nested rules succeed.

This is a schema-oriented alias for NewNoneRule. Example: `NoneOf(is.Email, is.UUID)` accepts `"plain-text"`.

func Not added in v1.167.0

func Not(rule validation.Rule) validation.Rule

Not returns a rule that succeeds only if rule fails.

This is a schema-oriented helper corresponding to JSON Schema `not`. Example: `Not(is.Email)` rejects `"user@example.com"`.

Reference: https://json-schema.org/understanding-json-schema/reference/combining#not

func NotContains added in v1.167.0

func NotContains(substring string) validation.Rule

NotContains validates that a string or byte slice does not contain substring.

func NotContainsWhitespaces added in v1.167.0

func NotContainsWhitespaces() validation.Rule

NotContainsWhitespaces validates that a string or byte slice contains no whitespace characters.

func NotEmpty added in v1.167.0

func NotEmpty() validation.Rule

NotEmpty validates that a value is not empty according to the repository's reflection-based emptiness semantics.

Example: `NotEmpty()` rejects `" "`.

func Nullable added in v1.167.0

func Nullable(rule validation.Rule) validation.Rule

Nullable validates that a value is nil or satisfies rule.

Example: `Nullable(Type("string"))` accepts `nil` and `"hello"`.

This is a convenience helper corresponding conceptually to JSON Schema patterns such as `type: ["string", "null"]` and to OpenAPI 3.0-style `nullable` handling. It is not a direct JSON Schema keyword.

References:

func OccursExactly added in v1.167.0

func OccursExactly(substring string, count int) validation.Rule

OccursExactly validates that substring occurs exactly count times in a string or byte slice.

func OneOf added in v1.167.0

func OneOf(rules ...validation.Rule) validation.Rule

OneOf returns a rule that succeeds only if exactly one nested rule succeeds.

Example: `OneOf(is.Email, is.UUID)` accepts a valid email or a valid UUID, but rejects values that satisfy both or neither rule.

Reference: https://json-schema.org/understanding-json-schema/reference/combining#oneof

func OneOfItemKeys added in v1.167.0

func OneOfItemKeys[T any, K comparable](keyFunc collection.KeyFunc[T, K], keys ...K) validation.Rule

OneOfItemKeys validates that a collection contains items matching exactly one of the supplied keys.

Example: `OneOfItemKeys(func(value user) string { return value.Role }, "admin", "editor")` accepts `[]user{{Role: "admin"}}` and rejects both `[]user{}` and `[]user{{Role: "admin"}, {Role: "editor"}}`.

func OneOfItems added in v1.167.0

func OneOfItems[T any, K comparable](keyFunc collection.KeyFunc[T, K], items ...T) validation.Rule

OneOfItems validates that a collection contains items matching exactly one of the supplied reference items.

Example: `OneOfItems(func(value string) string { return value }, "a", "b")` accepts `[]string{"a"}` and rejects both `[]string{}` and `[]string{"a", "b"}`.

func OneOfProperties added in v1.167.0

func OneOfProperties(keys ...string) validation.Rule

OneOfProperties validates that exactly one of the named keys or fields is set in a map or struct value.

Example: `OneOfProperties("A", "B")` accepts `{A: 1}` and rejects both `{}` and `{A: 1, B: 2}`.

This is not a direct JSON Schema keyword, but is useful for OpenAPI-like object validation.

OpenAPI reference: https://spec.openapis.org/oas/latest.html#schema-object

func OneOfPropertiesBy added in v1.167.0

func OneOfPropertiesBy(keys ...any) validation.Rule

OneOfPropertiesBy resolves strings, `[]string`, or field references against the validated value and applies OneOfProperties.

Example:

cfg := &Config{}
err := validation.Validate(cfg, OneOfPropertiesBy(&cfg.Token, &cfg.Username, &cfg.APIKey))

func Pattern added in v1.167.0

func Pattern(re *regexp.Regexp) validation.Rule

Pattern validates the JSON Schema `pattern` constraint.

JSON Schema applies `pattern` only to string instances. Non-string values are ignored rather than rejected. Unlike ozzo's `validation.Match(...)`, empty strings are still validated against the supplied regexp. Example: `Pattern(regexp.MustCompile("^[a-z]+$"))` accepts `"abc"`.

Reference: https://json-schema.org/understanding-json-schema/reference/string#regular-expressions

func PatternProperties added in v1.167.0

func PatternProperties(patterns ...PatternProperty) validation.Rule

PatternProperties validates the JSON Schema `patternProperties` constraint.

For each pattern/rule pair, every matching property name in a map or struct must have a value that satisfies the associated rule.

Example: a pattern `^s_` with rule `Type("string")` ensures every property whose name starts with `s_` contains a string value.

Reference: https://json-schema.org/understanding-json-schema/reference/object#pattern-properties

func Prefix added in v1.167.0

func Prefix(prefix string) validation.Rule

Prefix validates that a string or byte slice starts with prefix.

func PrefixItems added in v1.167.0

func PrefixItems(rules ...validation.Rule) validation.Rule

PrefixItems validates the JSON Schema `prefixItems` constraint.

Each rule is applied to the item at the same index. Extra items are ignored.

Example: `PrefixItems(Type("string"), Type("integer"))` accepts `[]any{"a", 1}`.

Reference: https://json-schema.org/understanding-json-schema/reference/array#tuple-validation

func PropertyNames added in v1.167.0

func PropertyNames(rule validation.Rule) validation.Rule

PropertyNames validates the JSON Schema `propertyNames` constraint.

The supplied rule is applied to every property name in a map or every field name in a struct.

Example: `PropertyNames(Pattern(regexp.MustCompile("^[a-z]+$")))` rejects a property named `Alpha`.

Reference: https://json-schema.org/understanding-json-schema/reference/object#property-names

func RequiredItemKeys added in v1.167.0

func RequiredItemKeys[T any, K comparable](keyFunc collection.KeyFunc[T, K], keys ...K) validation.Rule

RequiredItemKeys validates that a collection contains items matching all of the supplied keys derived by keyFunc.

Example: `RequiredItemKeys(func(value user) string { return value.Role }, "admin", "editor")` rejects `[]user{{Role: "admin"}}`.

func RequiredItems added in v1.167.0

func RequiredItems[T any, K comparable](keyFunc collection.KeyFunc[T, K], items ...T) validation.Rule

RequiredItems validates that a collection contains items matching all of the supplied reference items.

The comparison key for both the validated items and the reference items is derived with keyFunc.

Example: `RequiredItems(func(value string) string { return value }, "a", "b")` rejects `[]string{"a"}`.

func RequiredProperties added in v1.167.0

func RequiredProperties(keys ...string) validation.Rule

RequiredProperties validates the JSON Schema `required` constraint for object properties.

For map values, a property is considered present if the key exists. For structs, a property is considered present if a field of that name exists and its value is not empty according to the repository's reflection helpers.

Example: `RequiredProperties("a", "b")` rejects `map[string]any{"a": 1}`.

Reference: https://json-schema.org/understanding-json-schema/reference/object#required

func RequiredPropertiesBy added in v1.167.0

func RequiredPropertiesBy(keys ...any) validation.Rule

RequiredPropertiesBy resolves strings, `[]string`, or field references such as `&cfg.Name` against the validated value and applies RequiredProperties using the resulting property names.

String and `[]string` arguments are treated as literal keys. Field pointers are resolved back to their struct field names.

Example:

cfg := &Config{}
err := validation.Validate(cfg, RequiredPropertiesBy(&cfg.Name, &cfg.Enabled, &cfg.Mode))

func RuneLengthRule added in v1.167.0

func RuneLengthRule(min, max *int) validation.Rule

RuneLengthRule returns an ozzo rune-length rule with optional minimum and maximum bounds.

A nil minimum means zero. A nil maximum means unbounded.

Example: `RuneLengthRule(nil, field.ToOptionalInt(2))` accepts `éé` and rejects `ééé`.

Reference:

func Suffix added in v1.167.0

func Suffix(suffix string) validation.Rule

Suffix validates that a string or byte slice ends with suffix.

func TimestampConst added in v1.167.0

func TimestampConst(expected time.Time) validation.Rule

TimestampConst validates that a timestamp value is exactly equal to expected.

func TimestampExclusiveMaximum added in v1.167.0

func TimestampExclusiveMaximum(max time.Time) validation.Rule

TimestampExclusiveMaximum validates that a timestamp value is strictly before max.

func TimestampExclusiveMinimum added in v1.167.0

func TimestampExclusiveMinimum(min time.Time) validation.Rule

TimestampExclusiveMinimum validates that a timestamp value is strictly after min.

func TimestampMaximum added in v1.167.0

func TimestampMaximum(max time.Time) validation.Rule

TimestampMaximum validates that a timestamp value is less than or equal to max.

func TimestampMinimum added in v1.167.0

func TimestampMinimum(min time.Time) validation.Rule

TimestampMinimum validates that a timestamp value is greater than or equal to min.

func Type added in v1.167.0

func Type(types ...string) validation.Rule

Type validates the JSON Schema `type` constraint for decoded Go values.

Supported schema type names are: `string`, `number`, `integer`, `object`, `array`, `boolean`, and `null`.

Example: `Type("string", "null")` accepts a string value or nil.

Reference: https://json-schema.org/understanding-json-schema/reference/type

func UniqueItems added in v1.167.0

func UniqueItems[T any, K comparable](keyFunc collection.KeyFunc[T, K]) validation.Rule

UniqueItems validates the JSON Schema `unique_items` constraint using a key function to decide whether two items should be considered the same.

The provided key function should return a comparable identity for each item. If the number of items changes after applying collection.UniqueBy, the input contains duplicates.

Example: `UniqueItems[string](strings.ToLower)` rejects `[]string{"a", "A"}`.

Reference: https://json-schema.org/understanding-json-schema/reference/array#uniqueness

func WhenFieldEquals added in v1.167.0

func WhenFieldEquals(field any, expected any, rules ...validation.Rule) validation.Rule

WhenFieldEquals applies rules when the resolved field value equals expected.

Example:

cfg := &Config{}
err := validation.Validate(cfg, WhenFieldEquals(&cfg.Mode, "strict", RequiredPropertiesBy(&cfg.Name)))

func WhenFieldMatches added in v1.167.0

func WhenFieldMatches[T any](field any, expected T, match collection.MatchFunc[T], rules ...validation.Rule) validation.Rule

WhenFieldMatches applies rules when the resolved field value matches expected.

func WhenPropertyEquals added in v1.167.0

func WhenPropertyEquals(key string, expected any, rules ...validation.Rule) validation.Rule

WhenPropertyEquals applies rules when the value stored under key equals expected.

Equality is evaluated with `reflect.DeepEqual`.

Example: `WhenPropertyEquals("mode", "strict", RequiredProperties("name"))` validates `RequiredProperties("name")` only when `mode == "strict"`.

func WhenPropertyMatches added in v1.167.0

func WhenPropertyMatches[T any](key string, expected T, match collection.MatchFunc[T], rules ...validation.Rule) validation.Rule

WhenPropertyMatches applies rules when the value stored under key matches expected.

The comparison is delegated to match so callers can define case-insensitive or other domain-specific matching behaviour.

func XIntOrString added in v1.167.0

func XIntOrString() validation.Rule

XIntOrString validates the Kubernetes/OpenAPI `x-kubernetes-int-or-string` style constraint.

Example: `XIntOrString()` accepts `3`, `"3"`, and JSON-decoded integer numbers represented as `float64(3)`.

Types

type ICompositeRule added in v1.153.0

type ICompositeRule interface {
	// AppendRule adds one or more non-contextual rules to the composite rule.
	AppendRule(rule ...validation.Rule)

	// AppendContextualRule adds one or more context-aware rules to the
	// composite rule.
	AppendContextualRule(rule ...validation.RuleWithContext)

	validation.Rule
	validation.RuleWithContext
}

ICompositeRule represents a mutable logical rule set.

A ICompositeRule can combine both standard ozzo rules and context-aware rules, and can itself be used anywhere a validation.Rule or validation.RuleWithContext is accepted, including with validation.Validate.

func NewAllCompositeRule added in v1.153.0

func NewAllCompositeRule() ICompositeRule

NewAllCompositeRule returns an empty composite rule with AND semantics.

The returned rule succeeds only if all appended rules succeed, matching the behaviour of validation.Validate.

func NewAnyCompositeRule added in v1.153.0

func NewAnyCompositeRule() ICompositeRule

NewAnyCompositeRule returns an empty composite rule with OR semantics.

The returned rule succeeds if at least one appended rule succeeds, unlike validation.Validate which requires all supplied rules to succeed.

func NewAtLeastCompositeRule added in v1.167.0

func NewAtLeastCompositeRule(min int) ICompositeRule

NewAtLeastCompositeRule returns an empty composite rule that succeeds if at least min appended rules succeed.

func NewAtMostCompositeRule added in v1.167.0

func NewAtMostCompositeRule(max int) ICompositeRule

NewAtMostCompositeRule returns an empty composite rule that succeeds if no more than max appended rules succeed.

func NewExactlyCompositeRule added in v1.167.0

func NewExactlyCompositeRule(n int) ICompositeRule

NewExactlyCompositeRule returns an empty composite rule that succeeds if exactly `n` appended rules succeed.

func NewNoneCompositeRule added in v1.153.0

func NewNoneCompositeRule() ICompositeRule

NewNoneCompositeRule returns an empty composite rule with NONE semantics.

The returned rule succeeds only if none of the appended rules succeed.

func NewOneOfCompositeRule added in v1.167.0

func NewOneOfCompositeRule() ICompositeRule

NewOneOfCompositeRule returns an empty composite rule that succeeds if exactly one appended rule succeeds.

type PatternProperty added in v1.167.0

type PatternProperty struct {
	Pattern *regexp.Regexp
	Rule    validation.Rule
}

PatternProperty couples a property-name pattern with the rule that should be applied to matching properties.

Directories

Path Synopsis
Package jsonschema provides helpers for validating JSON and YAML content against JSON Schema documents.
Package jsonschema provides helpers for validating JSON and YAML content against JSON Schema documents.

Jump to

Keyboard shortcuts

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