limits.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /*
  2. Copyright 2024 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package validate
  14. import (
  15. "context"
  16. "k8s.io/apimachinery/pkg/api/operation"
  17. "k8s.io/apimachinery/pkg/api/validate/constraints"
  18. "k8s.io/apimachinery/pkg/api/validate/content"
  19. "k8s.io/apimachinery/pkg/util/validation/field"
  20. )
  21. // MaxLength verifies that the specified value is not longer than max
  22. // characters.
  23. func MaxLength[T ~string](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *T, max int) field.ErrorList {
  24. if value == nil {
  25. return nil
  26. }
  27. if len(*value) > max {
  28. return field.ErrorList{field.TooLong(fldPath, *value, max).WithOrigin("maxLength")}
  29. }
  30. return nil
  31. }
  32. // MaxItems verifies that the specified slice is not longer than max items.
  33. func MaxItems[T any](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ []T, max int) field.ErrorList {
  34. if len(value) > max {
  35. return field.ErrorList{field.TooMany(fldPath, len(value), max).WithOrigin("maxItems")}
  36. }
  37. return nil
  38. }
  39. // Minimum verifies that the specified value is greater than or equal to min.
  40. func Minimum[T constraints.Integer](_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *T, min T) field.ErrorList {
  41. if value == nil {
  42. return nil
  43. }
  44. if *value < min {
  45. return field.ErrorList{field.Invalid(fldPath, *value, content.MinError(min)).WithOrigin("minimum")}
  46. }
  47. return nil
  48. }