Documentation
¶
Overview ¶
- Copyright (C) 2020-2026 Arm Limited or its affiliates and Contributors. All rights reserved.
- SPDX-License-Identifier: Apache-2.0
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:
- ozzo-validation: https://github.com/go-ozzo/ozzo-validation
- ozzo-validation/is: https://github.com/go-ozzo/ozzo-validation/tree/master/is
Documentation:
Copyright (C) 2020-2026 Arm Limited or its affiliates and Contributors. All rights reserved.
SPDX-License-Identifier: Apache-2.0
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.
Copyright (C) 2020-2026 Arm Limited or its affiliates and Contributors. All rights reserved.
SPDX-License-Identifier: Apache-2.0
Copyright (C) 2020-2026 Arm Limited or its affiliates and Contributors. All rights reserved.
SPDX-License-Identifier: Apache-2.0
Copyright (C) 2020-2026 Arm Limited or its affiliates and Contributors. All rights reserved.
SPDX-License-Identifier: Apache-2.0
Copyright (C) 2020-2026 Arm Limited or its affiliates and Contributors. All rights reserved.
SPDX-License-Identifier: Apache-2.0
Copyright (C) 2020-2026 Arm Limited or its affiliates and Contributors. All rights reserved.
SPDX-License-Identifier: Apache-2.0
Copyright (C) 2020-2026 Arm Limited or its affiliates and Contributors. All rights reserved.
SPDX-License-Identifier: Apache-2.0
Copyright (C) 2020-2026 Arm Limited or its affiliates and Contributors. All rights reserved.
SPDX-License-Identifier: Apache-2.0
Index ¶
- Variables
- func AdditionalItemKeys[T any, K comparable](keyFunc collection.KeyFunc[T, K], keys ...K) validation.Rule
- func AdditionalItems[T any, K comparable](keyFunc collection.KeyFunc[T, K], items ...T) validation.Rule
- func AdditionalProperties(keys ...string) validation.Rule
- func AdditionalPropertiesBy(keys ...any) validation.Rule
- func AllOf(rules ...validation.Rule) validation.Rule
- func AnyOf(rules ...validation.Rule) validation.Rule
- func ArrayItems(rule validation.Rule) validation.Rule
- func AtLeast(min int, rule ...validation.Rule) validation.Rule
- func AtLeastOneFieldBy(fields ...any) validation.Rule
- func AtLeastOneItem[T any, K comparable](keyFunc collection.KeyFunc[T, K], items ...T) validation.Rule
- func AtLeastOneItemKey[T any, K comparable](keyFunc collection.KeyFunc[T, K], keys ...K) validation.Rule
- func AtLeastOneProperty(keys ...string) validation.Rule
- func AtLeastOnePropertyBy(keys ...any) validation.Rule
- func AtLeastWithContext(min int, rule ...validation.RuleWithContext) validation.RuleWithContext
- func AtMost(max int, rule ...validation.Rule) validation.Rule
- func AtMostOneItem[T any, K comparable](keyFunc collection.KeyFunc[T, K], items ...T) validation.Rule
- func AtMostOneItemKey[T any, K comparable](keyFunc collection.KeyFunc[T, K], keys ...K) validation.Rule
- func AtMostOneProperty(keys ...string) validation.Rule
- func AtMostOnePropertyBy(keys ...any) validation.Rule
- func AtMostWithContext(max int, rule ...validation.RuleWithContext) validation.RuleWithContext
- func Const(expected any) validation.Rule
- func Contains(rule validation.Rule) validation.Rule
- func ContainsString(substring string) validation.Rule
- func DependentRequired(dependencies map[string][]string) validation.Rule
- func DependentRequiredBy(dependencies map[any]any) validation.Rule
- func DependentRequiredItemKeys[T any, K comparable](keyFunc collection.KeyFunc[T, K], dependencies map[K][]K) validation.Rule
- func DependentRequiredItems[T comparable, K comparable](keyFunc collection.KeyFunc[T, K], dependencies map[T][]T) validation.Rule
- func DependentSchemas(dependencies map[string]validation.Rule) validation.Rule
- func DependentSchemasBy(dependencies map[any]validation.Rule) validation.Rule
- func DurationConst(expected time.Duration) validation.Rule
- func DurationExclusiveMaximum(max time.Duration) validation.Rule
- func DurationExclusiveMinimum(min time.Duration) validation.Rule
- func DurationMaximum(max time.Duration) validation.Rule
- func DurationMinimum(min time.Duration) validation.Rule
- func Enum(values ...any) validation.Rule
- func Exactly(n int, rule ...validation.Rule) validation.Rule
- func ExactlyWithContext(n int, rule ...validation.RuleWithContext) validation.RuleWithContext
- func ExclusiveMaximum(max any) validation.Rule
- func ExclusiveMinimum(min any) validation.Rule
- func FieldDependencyBy(dependencies map[any][]any) validation.Rule
- func ForbiddenFieldsBy(fields ...any) validation.Rule
- func ForbiddenItemKeys[T any, K comparable](keyFunc collection.KeyFunc[T, K], keys ...K) validation.Rule
- func ForbiddenItems[T any, K comparable](keyFunc collection.KeyFunc[T, K], items ...T) validation.Rule
- func ForbiddenProperties(keys ...string) validation.Rule
- func ForbiddenPropertiesBy(keys ...any) validation.Rule
- func IfThenElse(ifRule, thenRule, elseRule validation.Rule) validation.Rule
- func IfThenElseWithContext(ifRule, thenRule, elseRule validation.RuleWithContext) validation.RuleWithContext
- func Implies(antecedent, consequent validation.Rule) validation.Rule
- func ImpliesWithContext(antecedent, consequent validation.RuleWithContext) validation.RuleWithContext
- func LengthExact(n int) validation.Rule
- func LengthRule(min, max *int) validation.Rule
- func Like(re *regexp.Regexp) validation.Rule
- func MapKeys(rule validation.Rule) validation.Rule
- func MapValues(rule validation.Rule) validation.Rule
- func MaxContains(max int, rule validation.Rule) validation.Rule
- func MaxItems(max int) validation.Rule
- func MaxLength(max int) validation.Rule
- func MaxOccurs(substring string, max int) validation.Rule
- func MaxProperties(max int) validation.Rule
- func Maximum(max any) validation.Rule
- func MinContains(min int, rule validation.Rule) validation.Rule
- func MinItems(min int) validation.Rule
- func MinLength(min int) validation.Rule
- func MinOccurs(substring string, min int) validation.Rule
- func MinProperties(min int) validation.Rule
- func Minimum(min any) validation.Rule
- func MultipleOf(base any) validation.Rule
- func MutuallyExclusiveFieldsBy(fields ...any) validation.Rule
- func MutuallyExclusiveItemKeys[T any, K comparable](keyFunc collection.KeyFunc[T, K], keys ...K) validation.Rule
- func MutuallyExclusiveItems[T any, K comparable](keyFunc collection.KeyFunc[T, K], items ...T) validation.Rule
- func MutuallyExclusiveWith(keys ...string) validation.Rule
- func MutuallyExclusiveWithBy(keys ...any) validation.Rule
- func NOf(n int, rule ...validation.Rule) validation.Rule
- func NOfWithContext(n int, rule ...validation.RuleWithContext) validation.RuleWithContext
- func NewAllRule(rule ...validation.Rule) validation.Rule
- func NewAllRuleWithContext(rule ...validation.RuleWithContext) validation.RuleWithContext
- func NewAnyRule(rule ...validation.Rule) validation.Rule
- func NewAnyRuleWithContext(rule ...validation.RuleWithContext) validation.RuleWithContext
- func NewNoneRule(rule ...validation.Rule) validation.Rule
- func NewNoneRuleWithContext(rule ...validation.RuleWithContext) validation.RuleWithContext
- func NewOneOfRule(rule ...validation.Rule) validation.Rule
- func NewOneOfRuleWithContext(rule ...validation.RuleWithContext) validation.RuleWithContext
- func NoneOf(rules ...validation.Rule) validation.Rule
- func Not(rule validation.Rule) validation.Rule
- func NotContains(substring string) validation.Rule
- func NotContainsWhitespaces() validation.Rule
- func NotEmpty() validation.Rule
- func Nullable(rule validation.Rule) validation.Rule
- func OccursExactly(substring string, count int) validation.Rule
- func OneOf(rules ...validation.Rule) validation.Rule
- func OneOfFieldsBy(fields ...any) validation.Rule
- func OneOfItemKeys[T any, K comparable](keyFunc collection.KeyFunc[T, K], keys ...K) validation.Rule
- func OneOfItems[T any, K comparable](keyFunc collection.KeyFunc[T, K], items ...T) validation.Rule
- func OneOfProperties(keys ...string) validation.Rule
- func OneOfPropertiesBy(keys ...any) validation.Rule
- func Pattern(re *regexp.Regexp) validation.Rule
- func PatternProperties(patterns ...PatternProperty) validation.Rule
- func Prefix(prefix string) validation.Rule
- func PrefixItems(rules ...validation.Rule) validation.Rule
- func PropertyNames(rule validation.Rule) validation.Rule
- func RequiredFieldsBy(fields ...any) validation.Rule
- func RequiredItemKeys[T any, K comparable](keyFunc collection.KeyFunc[T, K], keys ...K) validation.Rule
- func RequiredItems[T any, K comparable](keyFunc collection.KeyFunc[T, K], items ...T) validation.Rule
- func RequiredProperties(keys ...string) validation.Rule
- func RequiredPropertiesBy(keys ...any) validation.Rule
- func RuneLengthRule(min, max *int) validation.Rule
- func SequenceItems(rule validation.Rule) validation.Rule
- func Suffix(suffix string) validation.Rule
- func TimestampConst(expected time.Time) validation.Rule
- func TimestampExclusiveMaximum(max time.Time) validation.Rule
- func TimestampExclusiveMinimum(min time.Time) validation.Rule
- func TimestampMaximum(max time.Time) validation.Rule
- func TimestampMinimum(min time.Time) validation.Rule
- func Type(types ...string) validation.Rule
- func UniqueItems[T any, K comparable](keyFunc collection.KeyFunc[T, K]) validation.Rule
- func WhenFieldAbsent(field any, rules ...validation.Rule) validation.Rule
- func WhenFieldEmpty(field any, rules ...validation.Rule) validation.Ruledeprecated
- func WhenFieldEquals(field any, expected any, rules ...validation.Rule) validation.Rule
- func WhenFieldEqualsValue(field any, expected any, rules ...validation.Rule) validation.Rule
- func WhenFieldInValues(field any, expected []any, rules ...validation.Rule) validation.Rule
- func WhenFieldMatches[T any](field any, expected T, match collection.MatchFunc[T], rules ...validation.Rule) validation.Rule
- func WhenFieldNotEmpty(field any, rules ...validation.Rule) validation.Ruledeprecated
- func WhenFieldNotEquals(field any, expected any, rules ...validation.Rule) validation.Rule
- func WhenFieldNotEqualsValue(field any, expected any, rules ...validation.Rule) validation.Rule
- func WhenFieldNotInValues(field any, expected []any, rules ...validation.Rule) validation.Rule
- func WhenFieldPresent(field any, rules ...validation.Rule) validation.Rule
- func WhenPropertyAbsent(key string, rules ...validation.Rule) validation.Rule
- func WhenPropertyEmpty(key string, rules ...validation.Rule) validation.Ruledeprecated
- func WhenPropertyEquals(key string, expected any, rules ...validation.Rule) validation.Rule
- func WhenPropertyMatches[T any](key string, expected T, match collection.MatchFunc[T], ...) validation.Rule
- func WhenPropertyNotEmpty(key string, rules ...validation.Rule) validation.Ruledeprecated
- func WhenPropertyNotEquals(key string, expected any, rules ...validation.Rule) validation.Rule
- func WhenPropertyPresent(key string, rules ...validation.Rule) validation.Rule
- func XIntOrString() validation.Rule
- type ICompositeRule
- func NewAllCompositeRule() ICompositeRule
- func NewAnyCompositeRule() ICompositeRule
- func NewAtLeastCompositeRule(min int) ICompositeRule
- func NewAtMostCompositeRule(max int) ICompositeRule
- func NewExactlyCompositeRule(n int) ICompositeRule
- func NewNoneCompositeRule() ICompositeRule
- func NewOneOfCompositeRule() ICompositeRule
- type PatternProperty
Constants ¶
This section is empty.
Variables ¶
var ( // ErrZeroRequired reports that the value must be the zero value for its type. ErrZeroRequired = validation.NewError("validation_zero_required", "must be zero") // ErrNotZeroRequired reports that the value must not be the zero value for its type. ErrNotZeroRequired = validation.NewError("validation_not_zero_required", "must not be zero") // ErrTrueRequired reports that the value must be true. ErrTrueRequired = validation.NewError("validation_true_required", "must be true") // ErrFalseRequired reports that the value must be false. ErrFalseRequired = validation.NewError("validation_false_required", "must be false") // ErrEmptyRequired reports that the value must be empty. ErrEmptyRequired = validation.NewError("validation_empty_required", "must be empty") // ErrNotEmptyRequired reports that the value must not be empty. ErrNotEmptyRequired = validation.NewError("validation_not_empty_required", "must not be empty") // ErrNilRequired reports that the value must be nil. ErrNilRequired = validation.NewError("validation_nil_required", "must be nil") // ErrNotNilRequired reports that the value must not be nil. ErrNotNilRequired = validation.NewError("validation_not_nil_required", "must not be nil") )
var IsBase64 = validation.NewStringRuleWithError(base64.IsEncoded, is.ErrBase64)
IsBase64 validates whether a value is a base64 encoded string. It is similar to is.Base64 but more generic and robust although less performant.
var IsDuration = validation.By(func(value any) error { if _, ok := durationValue(value); ok { return nil } return errInvalidDuration })
IsDuration validates whether a value is a valid Go duration.
It accepts duration strings and byte slices, as well as `time.Duration` values and their pointer forms.
var IsEmpty = validation.By(func(value any) error { if !isEmptyValue(value) { return ErrEmptyRequired } return nil })
IsEmpty validates that a value is empty according to golang-utils empty semantics.
var IsFalse = validation.By(func(value any) error { if valueBool, ok := value.(bool); ok && !valueBool { return nil } return ErrFalseRequired })
IsFalse validates that a value is false.
var IsNil = validation.Nil.ErrorObject(ErrNilRequired)
IsNil validates that a value is nil.
var IsNilOrNotEmpty = validation.By(func(value any) error { if isNilValue(value) { return nil } if isEmptyValue(value) { return validation.ErrNilOrNotEmpty } return nil })
IsNilOrNotEmpty validates that a value is either nil or not empty.
var IsNotEmpty = validation.By(func(value any) error { if isEmptyValue(value) { return ErrNotEmptyRequired } return nil })
IsNotEmpty validates that a value is not empty according to golang-utils empty semantics.
var IsNotNil = validation.NotNil.ErrorObject(ErrNotNilRequired)
IsNotNil validates that a value is not nil.
var IsNotNilAndNotEmpty = validation.By(func(value any) error { if err := IsNotNil.Validate(value); err != nil { return err } v, isNil := validation.Indirect(value) if isNil || isEmptyValue(v) { return ErrNotEmptyRequired } return nil })
IsNotNilAndNotEmpty validates that a value is both non-nil and non-empty.
var IsNotZero = validation.By(func(value any) error { if isZeroValue(value) { return ErrNotZeroRequired } return nil })
IsNotZero validates that a value is not the zero value for its type.
var IsPathParameter = urlutils.IsPathParameter
IsPathParameter validates OpenAPI-style path parameter segments such as `{id}`.
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.
var IsRFC3339Timestamp = validation.By(func(value any) error { if _, ok := timestampValue(value); ok { return nil } return errInvalidTimestamp })
IsRFC3339Timestamp validates whether a value is a valid RFC3339 timestamp.
It accepts RFC3339/RFC3339Nano strings and byte slices, as well as `time.Time` values and their pointer forms.
var IsRequired = IsRequiredLegacy
IsRequired preserves the legacy struct-friendly required semantics for callers that still expect the pre-v4.4 ozzo behaviour.
var IsRequiredLegacy = validation.By(func(value any) error { value, isNil := validation.Indirect(value) if isNil || isEmptyLegacy(value) { return validation.ErrRequired } return nil })
IsRequiredLegacy preserves the pre-v4.4 ozzo Required semantics where zero-valued structs other than time.Time{} are still considered present.
ozzo-validation v4.4.0 changed its empty-value detection so zero-valued structs now count as empty for Required/Empty semantics. See:
- https://github.com/go-ozzo/ozzo-validation/releases/tag/v4.4.0
- https://github.com/go-ozzo/ozzo-validation#empty-values
var IsTrue = validation.By(func(value any) error { if valueBool, ok := value.(bool); ok && valueBool { return nil } return ErrTrueRequired })
IsTrue validates that a value is true.
var IsURI = urlutils.IsURI
IsURI validates URI strings and byte slices.
var IsZero = validation.By(func(value any) error { if !isZeroValue(value) { return ErrZeroRequired } return nil })
IsZero validates that a value is the zero value for its type.
var NilTimestampOrNotEmpty = validation.By(func(value any) error { if isNilValue(value) { return nil } return timestampNotEmptyRule.Validate(value) })
NilTimestampOrNotEmpty validates that a timestamp value is either nil or a non-zero valid timestamp.
var Required = validation.By(validateRequiredValue)
Required validates that a value is present for state-style configuration use.
Unlike ozzo's `validation.Required`, this rule treats zero-valued structs, `false`, and numeric zero values as present. It rejects nil values, empty strings, and zero `time.Time{}` values.
This better aligns runtime value validation with the intent behind JSON Schema and OpenAPI `required`, where a field may be required even though its valid value can legitimately be `false`, `0`, or another zero value. In Go, once a property has been decoded into a struct field, this rule can be used to enforce that required-ness without incorrectly rejecting those valid zero values.
It should be noted that JSON Schema and OpenAPI `required` remain property-level concepts describing whether an object must define a named property, rather than whether an already-selected Go value should count as present.
References:
- JSON Schema object required properties: https://json-schema.org/understanding-json-schema/reference/object#required-properties
- OpenAPI Schema Object required: https://spec.openapis.org/oas/latest.html#schema-object
Functions ¶
func AdditionalItemKeys ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 AtLeastOneFieldBy ¶
func AtLeastOneFieldBy(fields ...any) validation.Rule
AtLeastOneFieldBy resolves field references on the validated value and validates that at least one of the resolved field values is non-empty.
func AtLeastOneItem ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
func ContainsString(substring string) validation.Rule
ContainsString validates that a string or byte slice contains substring.
func DependentRequired ¶
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 ¶
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:
payload := map[string]any{"username": "alice"}
err := validation.Validate(payload, DependentRequiredBy(map[any]any{"username": []any{"password", "scheme"}}))
This helper is best suited to property-oriented validation of maps or decoded object content where dependencies are expressed in terms of property existence. For struct validation where dependencies should be based on non-empty field values, prefer FieldDependencyBy. That is especially true when the struct has its own `Validate()` method and the rule is composed inside that method.
func DependentRequiredItemKeys ¶
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 ¶
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 ¶
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 ¶
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 ¶
func DurationConst(expected time.Duration) validation.Rule
DurationConst validates that a duration value is exactly equal to expected.
func DurationExclusiveMaximum ¶
func DurationExclusiveMaximum(max time.Duration) validation.Rule
DurationExclusiveMaximum validates that a duration value is strictly less than max.
func DurationExclusiveMinimum ¶
func DurationExclusiveMinimum(min time.Duration) validation.Rule
DurationExclusiveMinimum validates that a duration value is strictly greater than min.
func DurationMaximum ¶
func DurationMaximum(max time.Duration) validation.Rule
DurationMaximum validates that a duration value is less than or equal to max.
func DurationMinimum ¶
func DurationMinimum(min time.Duration) validation.Rule
DurationMinimum validates that a duration value is greater than or equal to min.
func Enum ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 FieldDependencyBy ¶
func FieldDependencyBy(dependencies map[any][]any) validation.Rule
FieldDependencyBy resolves field references on the validated value and requires the dependent fields to be non-empty whenever the source field is present.
Example:
cfg := &Config{}
err := validation.Validate(cfg, FieldDependencyBy(map[any][]any{&cfg.SummaryFile: {&cfg.Summary}}))
This rejects `cfg` when `cfg.SummaryFile` is non-empty but `cfg.Summary` is empty.
func ForbiddenFieldsBy ¶
func ForbiddenFieldsBy(fields ...any) validation.Rule
ForbiddenFieldsBy resolves field references on the validated value and validates that all resolved field values are empty.
func ForbiddenItemKeys ¶
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 ¶
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 ¶
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 ¶
func ForbiddenPropertiesBy(keys ...any) validation.Rule
ForbiddenPropertiesBy resolves strings, `[]string`, or field references against the validated value and applies ForbiddenProperties.
Example:
payload := map[string]any{"debug": true}
err := validation.Validate(payload, ForbiddenPropertiesBy("debug", "internalOnly"))
This helper is best suited to property-oriented validation of maps or decoded object content. For struct validation where forbiddenness should be based on non-empty field values, prefer ForbiddenFieldsBy. That is especially true when the struct has its own `Validate()` method and the rule is composed inside that method.
func IfThenElse ¶
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 ¶
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 ¶
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 ¶
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 ¶
func LengthExact(n int) validation.Rule
LengthExact validates that a length-aware value has exactly n elements.
func LengthRule ¶
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:
- JSON Schema string length: https://json-schema.org/understanding-json-schema/reference/string#length
- JSON Schema array length: https://json-schema.org/understanding-json-schema/reference/array#length
- JSON Schema object size: https://json-schema.org/understanding-json-schema/reference/object#size
func Like ¶
func Like(re *regexp.Regexp) validation.Rule
Like validates that a string or byte slice matches re.
func MapKeys ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 MutuallyExclusiveFieldsBy ¶
func MutuallyExclusiveFieldsBy(fields ...any) validation.Rule
MutuallyExclusiveFieldsBy resolves field references on the validated value and validates that at most one of the resolved field values is non-empty.
func MutuallyExclusiveItemKeys ¶
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 ¶
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 ¶
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 ¶
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:
payload := map[string]any{"token": "abc", "apiKey": "def"}
err := validation.Validate(payload, MutuallyExclusiveWithBy("token", "username", "apiKey"))
This helper is best suited to property-oriented validation of maps or decoded object content. For struct validation where exclusivity should be based on non-empty field values, prefer MutuallyExclusiveFieldsBy. That is especially true when the struct has its own `Validate()` method and the rule is composed inside that method.
func NOf ¶
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:
- Exactly-one style constraints in validation logic: https://en.wikipedia.org/wiki/Exclusive_or
- JSON Schema oneOf (related concept): https://json-schema.org/understanding-json-schema/reference/combining#oneof
It is a readability-oriented alias for Exactly.
func NOfWithContext ¶
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:
- Exactly-one style constraints in validation logic: https://en.wikipedia.org/wiki/Exclusive_or
- JSON Schema oneOf (related concept): https://json-schema.org/understanding-json-schema/reference/combining#oneof
It is a readability-oriented alias for ExactlyWithContext.
func NewAllRule ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
func NewOneOfRule(rule ...validation.Rule) validation.Rule
NewOneOfRule returns a rule that succeeds only if exactly one of the provided rules succeeds.
func NewOneOfRuleWithContext ¶
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 ¶
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 ¶
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 ¶
func NotContains(substring string) validation.Rule
NotContains validates that a string or byte slice does not contain substring.
func NotContainsWhitespaces ¶
func NotContainsWhitespaces() validation.Rule
NotContainsWhitespaces validates that a string or byte slice contains no whitespace characters.
func NotEmpty ¶
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 ¶
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:
- JSON Schema type reference: https://json-schema.org/understanding-json-schema/reference/type
- OpenAPI 3.0 Schema Object: https://spec.openapis.org/oas/v3.0.3.html#schema-object
func OccursExactly ¶
func OccursExactly(substring string, count int) validation.Rule
OccursExactly validates that substring occurs exactly count times in a string or byte slice.
func OneOf ¶
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 OneOfFieldsBy ¶
func OneOfFieldsBy(fields ...any) validation.Rule
OneOfFieldsBy resolves field references on the validated value and validates that exactly one of the resolved field values is non-empty.
func OneOfItemKeys ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
func Prefix(prefix string) validation.Rule
Prefix validates that a string or byte slice starts with prefix.
func PrefixItems ¶
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 ¶
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 RequiredFieldsBy ¶
func RequiredFieldsBy(fields ...any) validation.Rule
RequiredFieldsBy resolves strings, `[]string`, or field references such as `&cfg.Name` and validates that each resolved field value is non-empty.
This is the value-oriented counterpart to RequiredPropertiesBy. It is useful when the object shape is fixed (for example a struct) and the validation should require actual values rather than mere property presence.
Example:
cfg := &Config{}
err := validation.Validate(cfg, RequiredFieldsBy(&cfg.Name, &cfg.Mode))
This rejects `cfg` when either `cfg.Name` or `cfg.Mode` is empty, even though those struct fields are always present on the object.
func RequiredItemKeys ¶
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 ¶
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 ¶
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 ¶
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:
payload := map[string]any{"name": "alice", "enabled": true}
err := validation.Validate(payload, RequiredPropertiesBy("name", "enabled", "mode"))
This helper is best suited to property-oriented validation of maps or decoded object content where the question is whether properties exist at all. For struct validation where fields are always present but their values must be non-empty, prefer RequiredFieldsBy. That is especially true when the struct has its own `Validate()` method and the rule is composed inside that method.
func RuneLengthRule ¶
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:
- JSON Schema string length: https://json-schema.org/understanding-json-schema/reference/string#length
func SequenceItems ¶ added in v1.173.0
func SequenceItems(rule validation.Rule) validation.Rule
SequenceItems validates that every item in a function-backed sequence satisfies rule.
Example: `SequenceItems(Type("string"))` accepts `iter.Seq[any](func(yield func(any) bool) { ... })`.
func Suffix ¶
func Suffix(suffix string) validation.Rule
Suffix validates that a string or byte slice ends with suffix.
func TimestampConst ¶
func TimestampConst(expected time.Time) validation.Rule
TimestampConst validates that a timestamp value is exactly equal to expected.
func TimestampExclusiveMaximum ¶
func TimestampExclusiveMaximum(max time.Time) validation.Rule
TimestampExclusiveMaximum validates that a timestamp value is strictly before max.
func TimestampExclusiveMinimum ¶
func TimestampExclusiveMinimum(min time.Time) validation.Rule
TimestampExclusiveMinimum validates that a timestamp value is strictly after min.
func TimestampMaximum ¶
func TimestampMaximum(max time.Time) validation.Rule
TimestampMaximum validates that a timestamp value is less than or equal to max.
func TimestampMinimum ¶
func TimestampMinimum(min time.Time) validation.Rule
TimestampMinimum validates that a timestamp value is greater than or equal to min.
func Type ¶
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 ¶
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 WhenFieldAbsent ¶
func WhenFieldAbsent(field any, rules ...validation.Rule) validation.Rule
WhenFieldAbsent applies rules when the resolved field value is absent.
A field is considered absent when its value is empty according to `reflection.IsEmpty`.
Example:
cfg := &Config{}
err := validation.Validate(cfg, WhenFieldAbsent(&cfg.Token, RequiredFieldsBy(&cfg.Username)))
This requires `cfg.Username` whenever `cfg.Token` is empty.
func WhenFieldEmpty
deprecated
func WhenFieldEmpty(field any, rules ...validation.Rule) validation.Rule
WhenFieldEmpty applies rules when the resolved field value is empty.
Deprecated: prefer WhenFieldAbsent for schema-style presence checks.
func WhenFieldEquals ¶
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 WhenFieldEqualsValue ¶
func WhenFieldEqualsValue(field any, expected any, rules ...validation.Rule) validation.Rule
WhenFieldEqualsValue applies rules when the resolved field value equals expected.
It is the preferred value-oriented entrypoint for composing cross-field rules such as `RequiredFieldsBy(...)` against a containing struct.
The current implementation is equivalent to WhenFieldEquals, but this name makes the intended usage clearer when the nested rules validate field values rather than mere property presence.
Unlike older patterns that rely on `validation.When(...).Validate(value)`, the `WhenField...` helper family now executes nested rules directly against the containing object so it can be used safely from a struct's own `Validate()` implementation without recursive re-entry into that method.
Example:
cfg := &Config{}
err := validation.Validate(cfg, NewAllRule(
WhenFieldEqualsValue(&cfg.Mode, "strict", RequiredFieldsBy(&cfg.Name)),
WhenFieldPresent(&cfg.Name, RequiredFieldsBy(&cfg.Mode)),
))
func WhenFieldInValues ¶
func WhenFieldInValues(field any, expected []any, rules ...validation.Rule) validation.Rule
WhenFieldInValues applies rules when the resolved field value equals any of the supplied expected values.
Example:
cfg := &Config{}
err := validation.Validate(cfg, WhenFieldInValues(&cfg.Mode, []any{"strict", "relaxed"}, RequiredFieldsBy(&cfg.Profile)))
This requires `cfg.Profile` whenever `cfg.Mode` is either `strict` or `relaxed`.
func WhenFieldMatches ¶
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 WhenFieldNotEmpty
deprecated
func WhenFieldNotEmpty(field any, rules ...validation.Rule) validation.Rule
WhenFieldNotEmpty applies rules when the resolved field value is not empty.
Deprecated: prefer WhenFieldPresent for schema-style presence checks.
func WhenFieldNotEquals ¶
func WhenFieldNotEquals(field any, expected any, rules ...validation.Rule) validation.Rule
WhenFieldNotEquals applies rules when the resolved field value does not equal expected.
func WhenFieldNotEqualsValue ¶
func WhenFieldNotEqualsValue(field any, expected any, rules ...validation.Rule) validation.Rule
WhenFieldNotEqualsValue applies rules when the resolved field value does not equal expected.
It is the value-oriented counterpart to WhenFieldNotEquals.
Example:
cfg := &Config{}
err := validation.Validate(cfg, WhenFieldNotEqualsValue(&cfg.Mode, "strict", RequiredFieldsBy(&cfg.Profile)))
This requires `cfg.Profile` whenever `cfg.Mode != "strict"`.
func WhenFieldNotInValues ¶
func WhenFieldNotInValues(field any, expected []any, rules ...validation.Rule) validation.Rule
WhenFieldNotInValues applies rules when the resolved field value equals none of the supplied expected values.
Example:
cfg := &Config{}
err := validation.Validate(cfg, WhenFieldNotInValues(&cfg.Mode, []any{"strict", "relaxed"}, RequiredFieldsBy(&cfg.FallbackProfile)))
This requires `cfg.FallbackProfile` whenever `cfg.Mode` is neither `strict` nor `relaxed`.
func WhenFieldPresent ¶
func WhenFieldPresent(field any, rules ...validation.Rule) validation.Rule
WhenFieldPresent applies rules when the resolved field value is present.
A field is considered present when its value is not empty according to `reflection.IsNotEmpty`.
Example:
cfg := &Config{}
err := validation.Validate(cfg, WhenFieldPresent(&cfg.Token, ForbiddenFieldsBy(&cfg.Username)))
This rejects `cfg.Username` whenever `cfg.Token` is non-empty.
func WhenPropertyAbsent ¶
func WhenPropertyAbsent(key string, rules ...validation.Rule) validation.Rule
WhenPropertyAbsent applies rules when the value stored under key is absent.
A property is considered absent when it is missing or when its value is empty according to `reflection.IsEmpty`.
This helper is primarily intended for property-oriented validation of maps or decoded object content. For struct-oriented cross-field validation, prefer WhenFieldAbsent.
If the structure in question has its own `Validate()` method, prefer the field-oriented helpers for nested composition. They are designed to avoid the recursive re-entry pitfalls that older conditional-validation patterns can trigger.
Example: `WhenPropertyAbsent("token", RequiredProperties("username"))` requires `username` whenever `token` is missing or empty.
func WhenPropertyEmpty
deprecated
func WhenPropertyEmpty(key string, rules ...validation.Rule) validation.Rule
WhenPropertyEmpty applies rules when the value stored under key is empty.
Deprecated: prefer WhenPropertyAbsent for schema-style presence checks.
func WhenPropertyEquals ¶
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`.
This helper is primarily intended for property-oriented validation of maps or decoded object content where conditions are expressed in terms of named properties. For struct-oriented cross-field validation, prefer WhenFieldEqualsValue.
If the structure in question has its own `Validate()` method, prefer the field-oriented helpers for nested composition. They are designed to avoid the recursive re-entry pitfalls that older conditional-validation patterns can trigger.
Example: `WhenPropertyEquals("mode", "strict", RequiredProperties("name"))` validates `RequiredProperties("name")` only when `mode == "strict"`.
func WhenPropertyMatches ¶
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.
This helper is primarily intended for property-oriented validation of maps or decoded object content. For struct-oriented cross-field validation, prefer the corresponding `WhenField...` helpers.
If the structure in question has its own `Validate()` method, prefer the field-oriented helpers for nested composition. They are designed to avoid the recursive re-entry pitfalls that older conditional-validation patterns can trigger.
func WhenPropertyNotEmpty
deprecated
func WhenPropertyNotEmpty(key string, rules ...validation.Rule) validation.Rule
WhenPropertyNotEmpty applies rules when the value stored under key is not empty.
Deprecated: prefer WhenPropertyPresent for schema-style presence checks.
func WhenPropertyNotEquals ¶
func WhenPropertyNotEquals(key string, expected any, rules ...validation.Rule) validation.Rule
WhenPropertyNotEquals applies rules when the value stored under key does not equal expected.
Equality is evaluated with `reflect.DeepEqual`.
This helper is primarily intended for property-oriented validation of maps or decoded object content. For struct-oriented cross-field validation, prefer WhenFieldNotEqualsValue.
If the structure in question has its own `Validate()` method, prefer the field-oriented helpers for nested composition. They are designed to avoid the recursive re-entry pitfalls that older conditional-validation patterns can trigger.
Example: `WhenPropertyNotEquals("mode", "strict", ForbiddenProperties("name"))` rejects a payload that defines `name` unless `mode == "strict"`.
func WhenPropertyPresent ¶
func WhenPropertyPresent(key string, rules ...validation.Rule) validation.Rule
WhenPropertyPresent applies rules when the value stored under key is present.
A property is considered present when it exists and its value is not empty according to `reflection.IsNotEmpty`.
This helper is primarily intended for property-oriented validation of maps or decoded object content. For struct-oriented cross-field validation, prefer WhenFieldPresent.
If the structure in question has its own `Validate()` method, prefer the field-oriented helpers for nested composition. They are designed to avoid the recursive re-entry pitfalls that older conditional-validation patterns can trigger.
Example: `WhenPropertyPresent("token", ForbiddenProperties("username"))` rejects a payload that defines `username` whenever `token` is already set.
func XIntOrString ¶
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 ¶
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 ¶
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 ¶
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 ¶
func NewAtLeastCompositeRule(min int) ICompositeRule
NewAtLeastCompositeRule returns an empty composite rule that succeeds if at least min appended rules succeed.
func NewAtMostCompositeRule ¶
func NewAtMostCompositeRule(max int) ICompositeRule
NewAtMostCompositeRule returns an empty composite rule that succeeds if no more than max appended rules succeed.
func NewExactlyCompositeRule ¶
func NewExactlyCompositeRule(n int) ICompositeRule
NewExactlyCompositeRule returns an empty composite rule that succeeds if exactly `n` appended rules succeed.
func NewNoneCompositeRule ¶
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 ¶
func NewOneOfCompositeRule() ICompositeRule
NewOneOfCompositeRule returns an empty composite rule that succeeds if exactly one appended rule succeeds.
type PatternProperty ¶
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.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
* Copyright (C) 2020-2026 Arm Limited or its affiliates and Contributors.
|
* Copyright (C) 2020-2026 Arm Limited or its affiliates and Contributors. |
|
* Copyright (C) 2020-2026 Arm Limited or its affiliates and Contributors.
|
* Copyright (C) 2020-2026 Arm Limited or its affiliates and Contributors. |