validation

package
v2.4.9 Latest Latest
Warning

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

Go to latest
Published: Dec 11, 2024 License: Apache-2.0 Imports: 7 Imported by: 0

Documentation

Overview

Package validation implements a generic validator for values

Index

Examples

Constants

View Source
const (
	KeyDefault          = "default"
	KeyExamples         = "examples"
	KeyDescription      = "description"
	KeyTitle            = "title"
	KeyType             = "type"
	KeyConst            = "const"
	KeyEnum             = "enum"
	KeyMultipleOf       = "multipleOf"
	KeyMaximum          = "maximum"
	KeyMinimum          = "minimum"
	KeyExclusiveMaximum = "exclusiveMaximum"
	KeyExclusiveMinimum = "exclusiveMinimum"
	KeyMaxLength        = "maxLength"
	KeyMinLength        = "minLength"
	KeyPattern          = "pattern"
	KeyMaxItems         = "maxItems"
	KeyMinItems         = "minItems"
	KeyMaxProperties    = "maxProperties"
	KeyMinProperties    = "minProperties"
	KeyRequired         = "required"
	KeyPropertyNames    = "propertyNames"
	KeyProhibitUpdate   = "prohibitUpdate"
	KeyTFAttribute      = "tf_attribute"
	KeyTFAttributeSkip  = "tf_attribute_skip"
)
View Source
const CurrentField = ""

CurrentField is a constant to supply as a fieldPath for when there is a problem with the current field itself.

Variables

This section is empty.

Functions

This section is empty.

Types

type ConstraintBuilder

type ConstraintBuilder map[string]any

ConstraintBuilder - A builder for JSON Schema compliant constraint lists

func NewConstraintBuilder

func NewConstraintBuilder() ConstraintBuilder

NewConstraintBuilder creates a builder for JSON Schema compliant constraint lists. See http://json-schema.org/latest/json-schema-validation.html for types of validation available.

func (ConstraintBuilder) Build

func (cb ConstraintBuilder) Build() map[string]any

func (ConstraintBuilder) Const

func (cb ConstraintBuilder) Const(value any) ConstraintBuilder

Const adds a constraint that the field must equal this value.

func (ConstraintBuilder) Description

func (cb ConstraintBuilder) Description(desc string) ConstraintBuilder

Description adds a human-readable description

func (ConstraintBuilder) Enum

func (cb ConstraintBuilder) Enum(value ...any) ConstraintBuilder

Enum adds a constraint that the field must be one of these values.

func (ConstraintBuilder) Examples

func (cb ConstraintBuilder) Examples(ex ...any) ConstraintBuilder

Examples adds one or more examples

func (ConstraintBuilder) ExclusiveMaximum

func (cb ConstraintBuilder) ExclusiveMaximum(value int) ConstraintBuilder

ExclusiveMaximum adds a constraint that the field must be less than this number.

func (ConstraintBuilder) ExclusiveMinimum

func (cb ConstraintBuilder) ExclusiveMinimum(value int) ConstraintBuilder

ExclusiveMinimum adds a constraint that the field must be greater than this number.

func (ConstraintBuilder) MaxItems

func (cb ConstraintBuilder) MaxItems(value int) ConstraintBuilder

MaxItems adds a constraint that the array must have at most this many items.

func (ConstraintBuilder) MaxLength

func (cb ConstraintBuilder) MaxLength(value int) ConstraintBuilder

MaxLength adds a constraint that the string field must have at most this many characters.

func (ConstraintBuilder) MaxProperties

func (cb ConstraintBuilder) MaxProperties(value int) ConstraintBuilder

MaxProperties adds a constraint that the object must have at most this many keys.

func (ConstraintBuilder) Maximum

func (cb ConstraintBuilder) Maximum(value int) ConstraintBuilder

Maximum adds a constraint that the field must be less than or equal to this number.

func (ConstraintBuilder) MinItems

func (cb ConstraintBuilder) MinItems(value int) ConstraintBuilder

MinItems adds a constraint that the array must have at least this many items.

func (ConstraintBuilder) MinLength

func (cb ConstraintBuilder) MinLength(value int) ConstraintBuilder

MinLength adds a constraint that the string field must have at least this many characters.

func (ConstraintBuilder) MinProperties

func (cb ConstraintBuilder) MinProperties(value int) ConstraintBuilder

MinProperties adds a constraint that the object must have at least this many keys.

func (ConstraintBuilder) Minimum

func (cb ConstraintBuilder) Minimum(value int) ConstraintBuilder

Minimum adds a constraint that the field must be greater than or equal to this number.

func (ConstraintBuilder) MultipleOf

func (cb ConstraintBuilder) MultipleOf(value int) ConstraintBuilder

MultipleOf adds a constraint that the field must be a multiple of this integer.

func (ConstraintBuilder) Pattern

func (cb ConstraintBuilder) Pattern(value string) ConstraintBuilder

Pattern adds a constraint that the string must match the given pattern.

func (ConstraintBuilder) PropertyNames

func (cb ConstraintBuilder) PropertyNames(properties map[string]any) ConstraintBuilder

PropertyNames adds a constraint that the object property names must match the given schema.

func (ConstraintBuilder) Required

func (cb ConstraintBuilder) Required(properties ...string) ConstraintBuilder

Required adds a constraint that the object must have at least these keys.

func (ConstraintBuilder) Title

func (cb ConstraintBuilder) Title(title string) ConstraintBuilder

Title adds a human-readable label suitable for labeling a UI element.

func (ConstraintBuilder) Type

Type adds a type constrinat.

type FieldError

type FieldError struct {
	Message string
	Paths   []string
	// Details contains an optional longer payload.
	// +optional
	Details string
	// contains filtered or unexported fields
}

FieldError is used to propagate the context of errors pertaining to specific fields in a manner suitable for use in a recursive walk, so that errors contain the appropriate field context. FieldError methods are non-mutating. +k8s:deepcopy-gen=true

func ErrDisallowedFields

func ErrDisallowedFields(fieldPaths ...string) *FieldError

ErrDisallowedFields is a variadic helper method for constructing a FieldError for a set of disallowed fields.

func ErrDisallowedUpdateDeprecatedFields

func ErrDisallowedUpdateDeprecatedFields(fieldPaths ...string) *FieldError

ErrDisallowedUpdateDeprecatedFields is a variadic helper method for constructing a FieldError for updating of deprecated fields.

func ErrDuplicate

func ErrDuplicate(value string, fieldPaths ...string) *FieldError

ErrDuplicate constructs a FieldError for a field value that has been duplicated when it should have been unique

func ErrIfBlank

func ErrIfBlank(value, field string) *FieldError

ErrIfBlank returns an error if the value is a blank string.

func ErrIfDuplicate

func ErrIfDuplicate(value, field string, cache map[string]struct{}) *FieldError

ErrIfDuplicate returns error when a value is duplicated when it should be unique. State is stored in the cache which must be provided for every call in the set.

func ErrIfNil

func ErrIfNil(value any, field string) *FieldError

ErrIfNil returns an error if the value is nil.

func ErrIfNotHCL

func ErrIfNotHCL(value, field string) *FieldError

ErrIfNotHCL returns an error if the value is not valid HCL.

Example
fmt.Println("Good HCL is nil:", ErrIfNotHCL(`provider "google" {
		credentials = "${file("account.json")}"
		project     = "my-project-id"
		region      = "us-central1"
	}`, "my-field") == nil)

fmt.Println("Bad:", ErrIfNotHCL("google storage", "my-field"))
Output:

Good HCL is nil: true
Bad: invalid HCL: my-field

func ErrIfNotJSON

func ErrIfNotJSON(value json.RawMessage, field string) *FieldError

ErrIfNotJSON returns an error if the value is not valid JSON.

Example
fmt.Println("Good is nil:", ErrIfNotJSON(json.RawMessage("{}"), "my-field") == nil)
fmt.Println("Bad:", ErrIfNotJSON(json.RawMessage(""), "my-field"))
Output:

Good is nil: true
Bad: invalid JSON: my-field

func ErrIfNotJSONSchemaType

func ErrIfNotJSONSchemaType(value, field string) *FieldError

ErrIfNotJSONSchemaType returns an error if the value is not a valid JSON schema type.

Example
fmt.Println("Good is nil:", ErrIfNotJSONSchemaType("string", "my-field") == nil)
fmt.Println("Bad:", ErrIfNotJSONSchemaType("str", "my-field"))
Output:

Good is nil: true
Bad: field must match '^(|object|boolean|array|number|string|integer)$': my-field

func ErrIfNotMatch

func ErrIfNotMatch(value string, regex *regexp.Regexp, field string) *FieldError

ErrIfNotMatch returns an error if the value doesn't match the regex.

func ErrIfNotOSBName

func ErrIfNotOSBName(value, field string) *FieldError

ErrIfNotOSBName returns an error if the value is not a valid OSB name.

Example
fmt.Println("Good is nil:", ErrIfNotOSBName("google-storage", "my-field") == nil)
fmt.Println("Bad:", ErrIfNotOSBName("google storage", "my-field"))
Output:

Good is nil: true
Bad: field must match '^[a-zA-Z0-9-\.]+$': my-field

func ErrIfNotTerraformAttributePath

func ErrIfNotTerraformAttributePath(value, field string) *FieldError

ErrIfNotTerraformAttributePath returns an error if the value is not a valid Terraform identifier for an attribute in the HCL.

func ErrIfNotTerraformIdentifier

func ErrIfNotTerraformIdentifier(value, field string) *FieldError

ErrIfNotTerraformIdentifier returns an error if the value is not a valid Terraform identifier.

Example
fmt.Println("Good is nil:", ErrIfNotTerraformIdentifier("good_id", "my-field") == nil)
fmt.Println("Bad:", ErrIfNotTerraformIdentifier("bad id", "my-field"))
Output:

Good is nil: true
Bad: field must match '^[a-z_]*$': my-field

func ErrIfNotURL

func ErrIfNotURL(value, field string) *FieldError

ErrIfNotURL returns an error if the value is not a valid URL.

func ErrIfNotUUID

func ErrIfNotUUID(value, field string) *FieldError

ErrIfNotUUID returns an error if the value is not a valid UUID.

func ErrIfOutsideLength

func ErrIfOutsideLength(value, field string, min, max int) *FieldError

ErrIfOutsideLength returns an error if the length of the specified string is outside the specified length range

Example
fmt.Println("Good is within length:", ErrIfOutsideLength("four", "my-field", 2, 10) == nil)
fmt.Println("Good is at minimum:", ErrIfOutsideLength("four", "my-field", 4, 10) == nil)
fmt.Println("Good is at maximum:", ErrIfOutsideLength("four", "my-field", 1, 4) == nil)
fmt.Println("Bad is too short:", ErrIfOutsideLength("four", "my-field", 5, 10))
fmt.Println("Bad is too long:", ErrIfOutsideLength("four", "my-field", 1, 3))
Output:

Good is within length: true
Good is at minimum: true
Good is at maximum: true
Bad is too short: expected value to be 5-10 characters long, but got length 4: my-field
Bad is too long: expected value to be 1-3 characters long, but got length 4: my-field

func ErrInvalidArrayValue

func ErrInvalidArrayValue(value any, field string, index int) *FieldError

ErrInvalidArrayValue constructs a FieldError for a repetitive `field` at `index` that has received an invalid string value.

func ErrInvalidKeyName

func ErrInvalidKeyName(key, fieldPath string, details ...string) *FieldError

ErrInvalidKeyName is a variadic helper method for constructing a FieldError that specifies a key name that is invalid.

func ErrInvalidValue

func ErrInvalidValue(value any, fieldPath string) *FieldError

ErrInvalidValue constructs a FieldError for a field that has received an invalid string value.

func ErrMissingField

func ErrMissingField(fieldPaths ...string) *FieldError

ErrMissingField is a variadic helper method for constructing a FieldError for a set of missing fields.

func ErrMissingOneOf

func ErrMissingOneOf(fieldPaths ...string) *FieldError

ErrMissingOneOf is a variadic helper method for constructing a FieldError for not having at least one field in a mutually exclusive field group.

func ErrMultipleOneOf

func ErrMultipleOneOf(fieldPaths ...string) *FieldError

ErrMultipleOneOf is a variadic helper method for constructing a FieldError for having more than one field set in a mutually exclusive field group.

func ErrMustMatch

func ErrMustMatch(value string, regex *regexp.Regexp, field string) *FieldError

ErrMustMatch notifies the user a field must match a regex.

func ErrOutOfBoundsValue

func ErrOutOfBoundsValue(value, lower, upper any, fieldPath string) *FieldError

ErrOutOfBoundsValue constructs a FieldError for a field that has received an out of bound value.

func ErrOutsideLength

func ErrOutsideLength(value, lower, upper int, fieldPath string) *FieldError

ErrOutsideLength constructs a FieldError for a field that has received a value that is outside the range

func (*FieldError) Also

func (e *FieldError) Also(errs ...*FieldError) *FieldError

Also collects errors, returns a new collection of existing errors and new errors.

func (*FieldError) DeepCopy

func (e *FieldError) DeepCopy() *FieldError

DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new FieldError.

func (*FieldError) DeepCopyInto

func (e *FieldError) DeepCopyInto(out *FieldError)

DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.

func (*FieldError) Error

func (e *FieldError) Error() string

Error implements error

func (*FieldError) ViaField

func (e *FieldError) ViaField(prefix ...string) *FieldError

ViaField is used to propagate a validation error along a field access. For example, if a type recursively validates its "spec" via:

if err := foo.Spec.Validate(); err != nil {
  // Augment any field paths with the context that they were accessed
  // via "spec".
  return err.ViaField("spec")
}

func (*FieldError) ViaFieldIndex

func (e *FieldError) ViaFieldIndex(field string, index int) *FieldError

ViaFieldIndex is the short way to chain: err.ViaIndex(bar).ViaField(foo)

func (*FieldError) ViaFieldKey

func (e *FieldError) ViaFieldKey(field string, key string) *FieldError

ViaFieldKey is the short way to chain: err.ViaKey(bar).ViaField(foo)

func (*FieldError) ViaIndex

func (e *FieldError) ViaIndex(index int) *FieldError

ViaIndex is used to attach an index to the next ViaField provided. For example, if a type recursively validates a parameter that has a collection:

for i, c := range spec.Collection {
  if err := doValidation(c); err != nil {
    return err.ViaIndex(i).ViaField("collection")
  }
}

func (*FieldError) ViaKey

func (e *FieldError) ViaKey(key string) *FieldError

ViaKey is used to attach a key to the next ViaField provided. For example, if a type recursively validates a parameter that has a collection:

for k, v := range spec.Bag {
  if err := doValidation(v); err != nil {
    return err.ViaKey(k).ViaField("bag")
  }
}

type Testable

type Testable interface {
	Errorf(format string, a ...any)
}

Testable is a type derived from testing.T

type Validatable

type Validatable interface {
	// Validate checks the validity of this field type.
	Validate() *FieldError
}

Validatable indicates that a particular type may have its fields validated.

type ValidatableTest

type ValidatableTest struct {
	Object Validatable
	Expect error
}

ValidatableTest is a standard way of testing Validatable types.

func (*ValidatableTest) Assert

func (vt *ValidatableTest) Assert(t Testable)

Assert runs the validate function and fails Testable.

Jump to

Keyboard shortcuts

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