package validate
import "k8s.io/apimachinery/pkg/api/validate"
Package validate holds API validation functions which are designed for use with the k8s.io/code-generator/cmd/validation-gen tool. Each validation function has a similar fingerprint:
func <Name>(ctx context.Context,
op operation.Operation,
fldPath *field.Path,
value, oldValue <nilable type>,
<other args...>) field.ErrorList
The value and oldValue arguments will always be a nilable type. If the original value was a string, these will be a *string. If the original value was a slice or map, these will be the same slice or map type.
For a CREATE operation, the oldValue will always be nil. For an UPDATE operation, either value or oldValue may be nil, e.g. when adding or removing a value in a list-map. Validators which care about UPDATE operations should look at the opCtx argument to know which operation is being executed.
Tightened validation (also known as ratcheting validation) is supported by defining a new validation function. For example:
func TightenedMaxLength(ctx context.Context, op operation.Operation, fldPath *field.Path, value, oldValue *string) field.ErrorList {
if oldValue != nil && len(MaxLength(ctx, op, fldPath, oldValue, nil)) > 0 {
// old value is not valid, so this value skips the tightened validation
return nil
}
return MaxLength(ctx, op, fldPath, value, nil)
}
In general, we cannot distinguish a non-specified slice or map from one that is specified but empty. Validators should not rely on nil values, but use len() instead.
Index ¶
- func DirectEqual[T comparable](a, b T) bool
- func DirectEqualPtr[T comparable](a, b *T) bool
- func DiscriminatedUnion[T any, D ~string](_ context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj T, union *UnionMembership, discriminatorExtractor ExtractorFn[T, D], isSetFns ...ExtractorFn[T, bool]) (errs field.ErrorList)
- func EachMapKey[K ~string, T any](ctx context.Context, op operation.Operation, fldPath *field.Path, newMap, oldMap map[K]T, validator ValidateFunc[*K]) field.ErrorList
- func EachMapVal[K ~string, V any](ctx context.Context, op operation.Operation, fldPath *field.Path, newMap, oldMap map[K]V, equiv MatchFunc[V], validator ValidateFunc[*V]) field.ErrorList
- func EachSliceVal[T any](ctx context.Context, op operation.Operation, fldPath *field.Path, newSlice, oldSlice []T, match, equiv MatchFunc[T], validator ValidateFunc[*T]) field.ErrorList
- func Enum[T ~string](_ context.Context, op operation.Operation, fldPath *field.Path, value, _ *T, validValues sets.Set[T], exclusions []EnumExclusion[T]) field.ErrorList
- func ExtendedResourceName[T ~string](_ context.Context, op operation.Operation, fldPath *field.Path, value, _ *T) field.ErrorList
- func FixedResult[T any](_ context.Context, op operation.Operation, fldPath *field.Path, value, _ T, result bool, arg string) field.ErrorList
- func ForbiddenMap[K comparable, T any](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ map[K]T) field.ErrorList
- func ForbiddenPointer[T any](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *T) field.ErrorList
- func ForbiddenSlice[T any](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ []T) field.ErrorList
- func ForbiddenValue[T comparable](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *T) field.ErrorList
- func IfOption[T any](ctx context.Context, op operation.Operation, fldPath *field.Path, value, oldValue *T, optionName string, enabled bool, validator func(context.Context, operation.Operation, *field.Path, *T, *T) field.ErrorList, ) field.ErrorList
- func Immutable[T any](_ context.Context, op operation.Operation, fldPath *field.Path, _, _ T) field.ErrorList
- func LabelKey[T ~string](_ context.Context, op operation.Operation, fldPath *field.Path, value, _ *T) field.ErrorList
- func LabelValue[T ~string](_ context.Context, op operation.Operation, fldPath *field.Path, value, _ *T) field.ErrorList
- func LongName[T ~string](_ context.Context, op operation.Operation, fldPath *field.Path, value, _ *T) field.ErrorList
- func LongNameCaseless[T ~string](_ context.Context, op operation.Operation, fldPath *field.Path, value, _ *T) field.ErrorList
- func MaxItems[T any](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ []T, max int) field.ErrorList
- func MaxLength[T ~string](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *T, max int) field.ErrorList
- func Minimum[T constraints.Integer](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *T, min T) field.ErrorList
- func NEQ[T comparable](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *T, disallowed T) field.ErrorList
- func OptionalMap[K comparable, T any](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ map[K]T) field.ErrorList
- func OptionalPointer[T any](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *T) field.ErrorList
- func OptionalSlice[T any](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ []T) field.ErrorList
- func OptionalValue[T comparable](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *T) field.ErrorList
- func RequiredMap[K comparable, T any](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ map[K]T) field.ErrorList
- func RequiredPointer[T any](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *T) field.ErrorList
- func RequiredSlice[T any](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ []T) field.ErrorList
- func RequiredValue[T comparable](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *T) field.ErrorList
- func ResourceFullyQualifiedName[T ~string](ctx context.Context, op operation.Operation, fldPath *field.Path, value, _ *T) field.ErrorList
- func ResourcePoolName[T ~string](ctx context.Context, op operation.Operation, fldPath *field.Path, value, _ *T) field.ErrorList
- func SemanticDeepEqual[T any](a, b T) bool
- func ShortName[T ~string](_ context.Context, op operation.Operation, fldPath *field.Path, value, _ *T) field.ErrorList
- func SliceItem[TList ~[]TItem, TItem any]( ctx context.Context, op operation.Operation, fldPath *field.Path, newList, oldList TList, matches MatchItemFn[TItem], equiv MatchFunc[TItem], itemValidator func(ctx context.Context, op operation.Operation, fldPath *field.Path, newObj, oldObj *TItem) field.ErrorList, ) field.ErrorList
- func Subfield[Tstruct any, Tfield any]( ctx context.Context, op operation.Operation, fldPath *field.Path, newStruct, oldStruct *Tstruct, fldName string, getField GetFieldFunc[Tstruct, Tfield], equiv MatchFunc[Tfield], validator ValidateFunc[Tfield], ) field.ErrorList
- func UUID[T ~string](_ context.Context, op operation.Operation, fldPath *field.Path, value, _ *T) field.ErrorList
- func Union[T any](_ context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj T, union *UnionMembership, isSetFns ...ExtractorFn[T, bool]) field.ErrorList
- func Unique[T any](_ context.Context, _ operation.Operation, fldPath *field.Path, newSlice, _ []T, match MatchFunc[T]) field.ErrorList
- func UpdatePointer[T any](_ context.Context, op operation.Operation, fldPath *field.Path, value, oldValue *T, constraints ...UpdateConstraint) field.ErrorList
- func UpdateStruct[T any](_ context.Context, op operation.Operation, fldPath *field.Path, value, oldValue *T, constraints ...UpdateConstraint) field.ErrorList
- func UpdateValueByCompare[T comparable](_ context.Context, op operation.Operation, fldPath *field.Path, value, oldValue *T, constraints ...UpdateConstraint) field.ErrorList
- func UpdateValueByReflect[T any](_ context.Context, op operation.Operation, fldPath *field.Path, value, oldValue *T, constraints ...UpdateConstraint) field.ErrorList
- func ZeroOrOneOfUnion[T any](_ context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj T, union *UnionMembership, isSetFns ...ExtractorFn[T, bool]) field.ErrorList
- type EnumExclusion
- type ExtractorFn
- type GetFieldFunc
- type MatchFunc
- type MatchItemFn
- type UnionMember
- func NewDiscriminatedUnionMember(fieldName, discriminatorValue string) UnionMember
- func NewUnionMember(fieldName string) UnionMember
- type UnionMembership
- func NewDiscriminatedUnionMembership(discriminatorFieldName string, members ...UnionMember) *UnionMembership
- func NewUnionMembership(member ...UnionMember) *UnionMembership
- type UnionValidationOptions
- type UpdateConstraint
- type ValidateFunc
Functions ¶
func DirectEqual ¶
func DirectEqual[T comparable](a, b T) bool
DirectEqual is a MatchFunc that uses the == operator to compare two values. It can be used by any other function that needs to compare two values directly.
func DirectEqualPtr ¶
func DirectEqualPtr[T comparable](a, b *T) bool
DirectEqualPtr is a MatchFunc that dereferences two pointers and uses the == operator to compare the values. If both pointers are nil, it returns true. If one pointer is nil and the other is not, it returns false. It can be used by any other function that needs to compare two pointees directly.
func DiscriminatedUnion ¶
func DiscriminatedUnion[T any, D ~string](_ context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj T, union *UnionMembership, discriminatorExtractor ExtractorFn[T, D], isSetFns ...ExtractorFn[T, bool]) (errs field.ErrorList)
DiscriminatedUnion verifies specified union member matches the discriminator.
UnionMembership must define all the members of the union and the discriminator.
For example:
var UnionMembershipForABC = validate.NewDiscriminatedUnionMembership("type",
validate.NewDiscriminatedUnionMember("a", "A"),
validate.NewDiscriminatedUnionMember("b", "B"),
validate.NewDiscriminatedUnionMember("c", "C"),
)
func ValidateABC(ctx context.Context, op operation.Operation, fldPath *field.Path, in *ABC) (errs field.ErrorList) {
errs = append(errs, DiscriminatedUnion(ctx, op, fldPath, in, oldIn, UnionMembershipForABC,
func(in *ABC) string { return string(in.Type) },
func(in *ABC) bool { return in.A != nil },
func(in *ABC) bool { return in.B != "" },
func(in *ABC) bool { return in.C != 0 },
)...)
return errs
}
It is not an error for the discriminatorValue to be unknown. That must be validated on its own.
Note that T is "any", rather than "comparable", because union-members can be slices, meaning T might be a struct with a slice, meaning it is not comparable.
func EachMapKey ¶
func EachMapKey[K ~string, T any](ctx context.Context, op operation.Operation, fldPath *field.Path, newMap, oldMap map[K]T, validator ValidateFunc[*K]) field.ErrorList
EachMapKey validates each element of newMap with the specified validation function.
func EachMapVal ¶
func EachMapVal[K ~string, V any](ctx context.Context, op operation.Operation, fldPath *field.Path, newMap, oldMap map[K]V, equiv MatchFunc[V], validator ValidateFunc[*V]) field.ErrorList
EachMapVal validates each value in newMap using the specified validation function, passing the corresponding old value from oldMap if the key exists in oldMap. For update operations, it implements validation ratcheting by skipping validation when the old value exists and the equiv function confirms the values are equivalent. The value-type of the map is assumed to not be nilable. If equiv is nil, value-based ratcheting is disabled and all values will be validated.
func EachSliceVal ¶
func EachSliceVal[T any](ctx context.Context, op operation.Operation, fldPath *field.Path, newSlice, oldSlice []T, match, equiv MatchFunc[T], validator ValidateFunc[*T]) field.ErrorList
EachSliceVal performs validation on each element of newSlice using the provided validation function.
For update operations, the match function finds corresponding values in oldSlice for each value in newSlice. This comparison can be either full or partial (e.g., matching only specific struct fields that serve as a unique identifier). If match is nil, validation proceeds without considering old values, and the equiv function is not used.
For update operations, the equiv function checks if a new value is equivalent to its corresponding old value, enabling validation ratcheting. If equiv is nil but match is provided, the match function is assumed to perform full value comparison.
Note: The slice element type must be non-nilable.
func Enum ¶
func Enum[T ~string](_ context.Context, op operation.Operation, fldPath *field.Path, value, _ *T, validValues sets.Set[T], exclusions []EnumExclusion[T]) field.ErrorList
Enum verifies that a given value is a member of a set of enum values. Exclude Rules that apply when options are enabled or disabled are also considered. If ANY exclude rule matches for a value, that value is excluded from the enum when validating.
func ExtendedResourceName ¶
func ExtendedResourceName[T ~string](_ context.Context, op operation.Operation, fldPath *field.Path, value, _ *T) field.ErrorList
ExtendedResourceName verifies that the specified value is a valid extended resource name. An extended resource name is a domain-prefixed name that does not use the "kubernetes.io" or "requests." prefixes. Must be a valid label key when appended to "requests.", as in quota.
- must have slash domain and name.
- must not have the "kubernetes.io" domain
- must not have the "requests." prefix
- name must be 63 characters or less
- must be a valid label key when appended to "requests.", as in quota -- must contain only alphanumeric characters, dashes, underscores, or dots -- must end with an alphanumeric character
func FixedResult ¶
func FixedResult[T any](_ context.Context, op operation.Operation, fldPath *field.Path, value, _ T, result bool, arg string) field.ErrorList
FixedResult asserts a fixed boolean result. This is mostly useful for testing.
func ForbiddenMap ¶
func ForbiddenMap[K comparable, T any](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ map[K]T) field.ErrorList
ForbiddenMap verifies that the specified map is empty.
func ForbiddenPointer ¶
func ForbiddenPointer[T any](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *T) field.ErrorList
ForbiddenPointer verifies that the specified pointer is nil.
func ForbiddenSlice ¶
func ForbiddenSlice[T any](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ []T) field.ErrorList
ForbiddenSlice verifies that the specified slice is empty.
func ForbiddenValue ¶
func ForbiddenValue[T comparable](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *T) field.ErrorList
ForbiddenValue verifies that the specified value is the zero-value for its type.
func IfOption ¶
func IfOption[T any](ctx context.Context, op operation.Operation, fldPath *field.Path, value, oldValue *T, optionName string, enabled bool, validator func(context.Context, operation.Operation, *field.Path, *T, *T) field.ErrorList, ) field.ErrorList
IfOption conditionally evaluates a validation function. If the option and enabled are both true the validator is called. If the option and enabled are both false the validator is called. Otherwise, the validator is not called.
func Immutable ¶
func Immutable[T any](_ context.Context, op operation.Operation, fldPath *field.Path, _, _ T) field.ErrorList
Immutable verifies that the specified value has not changed in the course of an update operation. It does nothing if the old value is not provided.
This function unconditionally returns a validation error as it relies on the default ratcheting mechanism to only be called when a change to the field has already been detected. This avoids a redundant equivalence check across ratcheting and this function.
func LabelKey ¶
func LabelKey[T ~string](_ context.Context, op operation.Operation, fldPath *field.Path, value, _ *T) field.ErrorList
LabelKey verifies that the specified value is a valid label key. A label key is composed of an optional prefix and a name, separated by a '/'. The name part is required and must:
- be 63 characters or less
- begin and end with an alphanumeric character ([a-z0-9A-Z])
- contain only alphanumeric characters, dashes (-), underscores (_), or dots (.)
The prefix is optional and must:
- be a DNS subdomain
- be no more than 253 characters
func LabelValue ¶
func LabelValue[T ~string](_ context.Context, op operation.Operation, fldPath *field.Path, value, _ *T) field.ErrorList
LabelValue verifies that the specified value is a valid label value.
- can be empty
- must be no more than 63 characters
- must start and end with alphanumeric characters
- must contain only alphanumeric characters, dashes, underscores, or dots
func LongName ¶
func LongName[T ~string](_ context.Context, op operation.Operation, fldPath *field.Path, value, _ *T) field.ErrorList
LongName verifies that the specified value is a valid "long name" (sometimes known as a "DNS subdomain").
- must not be empty
- must be less than 254 characters long
- each element must start and end with lower-case alphanumeric characters
- each element must contain only lower-case alphanumeric characters or dashes
All errors returned by this function will be "invalid" type errors. If the caller wants better errors, it must take responsibility for checking things like required/optional and max-length.
func LongNameCaseless ¶
func LongNameCaseless[T ~string](_ context.Context, op operation.Operation, fldPath *field.Path, value, _ *T) field.ErrorList
LongNameCaseless verifies that the specified value is a valid "long name" (sometimes known as a "DNS subdomain"), but is case-insensitive.
- must not be empty
- must be less than 254 characters long
- each element must start and end with alphanumeric characters
- each element must contain only alphanumeric characters or dashes
Deprecated: Case-insensitive names are not recommended as they can lead to ambiguity (e.g., 'Foo', 'FOO', and 'foo' would be allowed names for foo). Use LongName for strict, lowercase validation.
func MaxItems ¶
func MaxItems[T any](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ []T, max int) field.ErrorList
MaxItems verifies that the specified slice is not longer than max items.
func MaxLength ¶
func MaxLength[T ~string](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *T, max int) field.ErrorList
MaxLength verifies that the specified value is not longer than max characters.
func Minimum ¶
func Minimum[T constraints.Integer](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *T, min T) field.ErrorList
Minimum verifies that the specified value is greater than or equal to min.
func NEQ ¶
func NEQ[T comparable](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *T, disallowed T) field.ErrorList
NEQ validates that the specified comparable value is not equal to the disallowed value.
func OptionalMap ¶
func OptionalMap[K comparable, T any](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ map[K]T) field.ErrorList
OptionalMap verifies that the specified map is not empty. This is identical to RequiredMap, but the caller should treat an error here as an indication that the optional value was not specified.
func OptionalPointer ¶
func OptionalPointer[T any](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *T) field.ErrorList
OptionalPointer verifies that the specified pointer is not nil. This is identical to RequiredPointer, but the caller should treat an error here as an indication that the optional value was not specified.
func OptionalSlice ¶
func OptionalSlice[T any](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ []T) field.ErrorList
OptionalSlice verifies that the specified slice is not empty. This is identical to RequiredSlice, but the caller should treat an error here as an indication that the optional value was not specified.
func OptionalValue ¶
func OptionalValue[T comparable](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *T) field.ErrorList
OptionalValue verifies that the specified value is not the zero-value for its type. This is identical to RequiredValue, but the caller should treat an error here as an indication that the optional value was not specified.
func RequiredMap ¶
func RequiredMap[K comparable, T any](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ map[K]T) field.ErrorList
RequiredMap verifies that the specified map is not empty.
func RequiredPointer ¶
func RequiredPointer[T any](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *T) field.ErrorList
RequiredPointer verifies that the specified pointer is not nil.
func RequiredSlice ¶
func RequiredSlice[T any](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ []T) field.ErrorList
RequiredSlice verifies that the specified slice is not empty.
func RequiredValue ¶
func RequiredValue[T comparable](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *T) field.ErrorList
RequiredValue verifies that the specified value is not the zero-value for its type.
func ResourceFullyQualifiedName ¶
func ResourceFullyQualifiedName[T ~string](ctx context.Context, op operation.Operation, fldPath *field.Path, value, _ *T) field.ErrorList
ResourceFullyQualifiedName verifies that the specified value is a valid Kubernetes fully qualified name.
- must not be empty
- must be composed of a prefix and a name, separated by a slash (e.g., "prefix/name")
- the prefix must be a DNS subdomain
- the name part must be a C identifier
- the name part must be no more than 32 characters
func ResourcePoolName ¶
func ResourcePoolName[T ~string](ctx context.Context, op operation.Operation, fldPath *field.Path, value, _ *T) field.ErrorList
ResourcePoolName verifies that the specified value is one or more valid "long name" parts separated by a '/' and no longer than 253 characters.
func SemanticDeepEqual ¶
SemanticDeepEqual is a MatchFunc that uses equality.Semantic.DeepEqual to compare two values. This wrapper is needed because MatchFunc requires a function that takes two arguments of specific type T, while equality.Semantic.DeepEqual takes arguments of type interface{}/any. The wrapper satisfies the type constraints of MatchFunc while leveraging the underlying semantic equality logic. It can be used by any other function that needs to call DeepEqual.
func ShortName ¶
func ShortName[T ~string](_ context.Context, op operation.Operation, fldPath *field.Path, value, _ *T) field.ErrorList
ShortName verifies that the specified value is a valid "short name" (sometimes known as a "DNS label").
- must not be empty
- must be less than 64 characters long
- must start and end with lower-case alphanumeric characters
- must contain only lower-case alphanumeric characters or dashes
All errors returned by this function will be "invalid" type errors. If the caller wants better errors, it must take responsibility for checking things like required/optional and max-length.
func SliceItem ¶
func SliceItem[TList ~[]TItem, TItem any]( ctx context.Context, op operation.Operation, fldPath *field.Path, newList, oldList TList, matches MatchItemFn[TItem], equiv MatchFunc[TItem], itemValidator func(ctx context.Context, op operation.Operation, fldPath *field.Path, newObj, oldObj *TItem) field.ErrorList, ) field.ErrorList
SliceItem finds the first item in newList that satisfies the match function, and if found, also looks for a matching item in oldList. If the value of the item is the same as the previous value, as per the equiv function, then no validation is performed. Otherwise, it invokes 'itemValidator' on these items.
This function processes only the *first* matching item found in newList. It assumes that the match functions targets a unique identifier (primary key) and will match at most one element per list. If this assumption is violated, changes in list order can lead this function to have inconsistent behavior.
The fldPath passed to itemValidator is indexed to the matched item's position in newList.
This function does not validate items that were removed (present in oldList but not in newList).
func Subfield ¶
func Subfield[Tstruct any, Tfield any]( ctx context.Context, op operation.Operation, fldPath *field.Path, newStruct, oldStruct *Tstruct, fldName string, getField GetFieldFunc[Tstruct, Tfield], equiv MatchFunc[Tfield], validator ValidateFunc[Tfield], ) field.ErrorList
Subfield validates a subfield of a struct against a validator function. If the value of the subfield is the same as the previous value, as per the equiv function, then no validation is performed.
The fldPath passed to the validator includes the subfield name.
func UUID ¶
func UUID[T ~string](_ context.Context, op operation.Operation, fldPath *field.Path, value, _ *T) field.ErrorList
UUID verifies that the specified value is a valid UUID (RFC 4122).
- must be 36 characters long
- must be in the normalized form `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`
- must use only lowercase hexadecimal characters
func Union ¶
func Union[T any](_ context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj T, union *UnionMembership, isSetFns ...ExtractorFn[T, bool]) field.ErrorList
Union verifies that exactly one member of a union is specified.
UnionMembership must define all the members of the union.
For example:
var UnionMembershipForABC := validate.NewUnionMembership(
validate.NewUnionMember("a"),
validate.NewUnionMember("b"),
validate.NewUnionMember("c"),
)
func ValidateABC(ctx context.Context, op operation.Operation, fldPath *field.Path, in *ABC) (errs field.ErrorList) {
errs = append(errs, Union(ctx, op, fldPath, in, oldIn, UnionMembershipForABC,
func(in *ABC) bool { return in.A != nil },
func(in *ABC) bool { return in.B != "" },
func(in *ABC) bool { return in.C != 0 },
)...)
return errs
}
Note that T is "any", rather than "comparable", because union-members can be slices, meaning T might be a struct with a slice, meaning it is not comparable.
func Unique ¶
func Unique[T any](_ context.Context, _ operation.Operation, fldPath *field.Path, newSlice, _ []T, match MatchFunc[T]) field.ErrorList
Unique verifies that each element of newSlice is unique, according to the match function. It compares every element of the slice with every other element and returns errors for non-unique items.
func UpdatePointer ¶
func UpdatePointer[T any](_ context.Context, op operation.Operation, fldPath *field.Path, value, oldValue *T, constraints ...UpdateConstraint) field.ErrorList
UpdatePointer verifies update constraints for pointer types.
func UpdateStruct ¶
func UpdateStruct[T any](_ context.Context, op operation.Operation, fldPath *field.Path, value, oldValue *T, constraints ...UpdateConstraint) field.ErrorList
UpdateStruct verifies update constraints for non-pointer struct types. Non-pointer structs are always considered "set" and never "unset".
func UpdateValueByCompare ¶
func UpdateValueByCompare[T comparable](_ context.Context, op operation.Operation, fldPath *field.Path, value, oldValue *T, constraints ...UpdateConstraint) field.ErrorList
UpdateValueByCompare verifies update constraints for comparable value types.
func UpdateValueByReflect ¶
func UpdateValueByReflect[T any](_ context.Context, op operation.Operation, fldPath *field.Path, value, oldValue *T, constraints ...UpdateConstraint) field.ErrorList
UpdateValueByReflect verifies update constraints for non-comparable value types using reflection.
func ZeroOrOneOfUnion ¶
func ZeroOrOneOfUnion[T any](_ context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj T, union *UnionMembership, isSetFns ...ExtractorFn[T, bool]) field.ErrorList
ZeroOrOneOfUnion verifies that at most one member of a union is specified.
ZeroOrOneOfMembership must define all the members of the union.
For example:
var ZeroOrOneOfMembershipForABC = validate.NewUnionMembership(
validate.NewUnionMember("a"),
validate.NewUnionMember("b"),
validate.NewUnionMember("c"),
)
func ValidateABC(ctx context.Context, op operation.Operation, fldPath *field.Path, in *ABC) (errs field.ErrorList) {
errs = append(errs, validate.ZeroOrOneOfUnion(ctx, op, fldPath, in, oldIn,
ZeroOrOneOfMembershipForABC,
func(in *ABC) bool { return in.A != nil },
func(in *ABC) bool { return in.B != ""},
func(in *ABC) bool { return in.C != 0 },
)...)
return errs
}
Types ¶
type EnumExclusion ¶
type EnumExclusion[T ~string] struct { // Value specifies the enum value to be conditionally excluded. Value T // ExcludeWhen determines the condition for exclusion. // If true, the value is excluded if the option is present. // If false, the value is excluded if the option is NOT present. ExcludeWhen bool // Option is the name of the feature option that controls the exclusion. Option string }
EnumExclusion represents a single enum exclusion rule.
type ExtractorFn ¶
type ExtractorFn[T, V any] func(obj T) V
ExtractorFn extracts a value from a parent object. Depending on the context, that could be the value of a field or just whether that field was set or not. Note: obj is not guaranteed to be non-nil, need to handle nil obj in the extractor.
type GetFieldFunc ¶
GetFieldFunc is a function that extracts a field from a type and returns a nilable value.
type MatchFunc ¶
MatchFunc is a function that compares two values of the same type, according to some criteria, and returns true if they match.
type MatchItemFn ¶
MatchItemFn takes a pointer to an item and returns true if it matches the criteria.
type UnionMember ¶
type UnionMember struct {
// contains filtered or unexported fields
}
UnionMember represents a member of a union.
func NewDiscriminatedUnionMember ¶
func NewDiscriminatedUnionMember(fieldName, discriminatorValue string) UnionMember
NewDiscriminatedUnionMember returns a new UnionMember for the given field name and discriminator value.
func NewUnionMember ¶
func NewUnionMember(fieldName string) UnionMember
NewUnionMember returns a new UnionMember for the given field name.
type UnionMembership ¶
type UnionMembership struct {
// contains filtered or unexported fields
}
UnionMembership represents an ordered list of field union memberships.
func NewDiscriminatedUnionMembership ¶
func NewDiscriminatedUnionMembership(discriminatorFieldName string, members ...UnionMember) *UnionMembership
NewDiscriminatedUnionMembership returns a new UnionMembership for the given discriminator field and list of members. members are provided in the same way as for NewUnionMembership.
func NewUnionMembership ¶
func NewUnionMembership(member ...UnionMember) *UnionMembership
NewUnionMembership returns a new UnionMembership for the given list of members. Member names must be unique.
type UnionValidationOptions ¶
type UnionValidationOptions struct {
// ErrorForEmpty returns error when no fields are set (nil means no error)
ErrorForEmpty func(fldPath *field.Path, allFields []string) *field.Error
// ErrorForMultiple returns error when multiple fields are set (nil means no error)
ErrorForMultiple func(fldPath *field.Path, specifiedFields []string, allFields []string) *field.Error
}
UnionValidationOptions configures how union validation behaves
type UpdateConstraint ¶
type UpdateConstraint int
UpdateConstraint represents a constraint on update operations
const ( // NoSet prevents unset->set transitions NoSet UpdateConstraint = iota // NoUnset prevents set->unset transitions NoUnset // NoModify prevents value changes but allows set/unset transitions NoModify )
type ValidateFunc ¶
type ValidateFunc[T any] func(ctx context.Context, op operation.Operation, fldPath *field.Path, newValue, oldValue T) field.ErrorList
ValidateFunc is a function that validates a value, possibly considering the old value (if any).
Source Files ¶
common.go doc.go each.go enum.go equality.go immutable.go item.go limits.go options.go required.go strfmt.go subfield.go testing.go union.go update.go zeroorone.go
Directories ¶
| Path | Synopsis |
|---|---|
| pkg/api/validate/constraints | |
| pkg/api/validate/content |
- Version
- v0.35.4
- Published
- Apr 14, 2026
- Platform
- windows/amd64
- Imports
- 12 packages
- Last checked
- 6 seconds ago –
Tools for package owners.