validation

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Jun 10, 2024 License: MIT Imports: 11 Imported by: 0

README

go-validation

Simple and flexible Go (Golang) validation library.

This library provides an elegant DSL for defining validation constraints in Go.

Installation

Pull in the library using go get:

$ go get github.com/seeruk/go-validation

License

MIT

Documentation

Index

Constants

View Source
const DefaultNameStructTag = "validation"

DefaultNameStructTag is the default struct tag used to override the name of struct fields in the path that's output.

Variables

This section is empty.

Functions

func ConstraintViolationsToProto

func ConstraintViolationsToProto(violations []ConstraintViolation) []protoadapt.MessageV1

ConstraintViolationsToProto converts a slice of ConstraintViolations into a slice of the ProtoBuf representation of those ConstraintViolations, making them ready to use for example in a gRPC service in a similar way to how ConstraintViolation can already be used in JSON web services.

They're returned as a slice of proto.Message so that they can be passed straight into something like a gRPC status without transformation.

func CreateValidateFunc added in v0.1.8

func CreateValidateFunc(structTag string) func(value interface{}, constraints ...Constraint) []ConstraintViolation

CreateValidateFunc allows the caller to create a customised validate function, using the given option(s), allowing them to avoid manually creating a context and using the simpler API while maintaining the ability to customise the validation context. TODO: Any more options to add?

func FieldName

func FieldName(ctx Context, fieldName string) string

FieldName returns the output name for a field of the given field name. The provided Context's value must be a struct, or this function will panic. FieldName will unwrap the value on the given Context, like many Constraints do.

func IsEmpty

func IsEmpty(value reflect.Value) bool

IsEmpty checks if a value is "empty". Basically, if it's a value's zero value, nil, or has no length it's considered empty.

func IsNillable

func IsNillable(value reflect.Value) bool

IsNillable returns true if the given value is of a nillable type.

func MustBe

func MustBe(typ reflect.Type, kinds ...reflect.Kind)

MustBe will panic if the given reflect.Value is not one of the given reflect.Kind kinds.

func UnwrapType

func UnwrapType(typ reflect.Type) reflect.Type

UnwrapType takes the given reflect.Type, and if it's a pointer gets the pointer element's type. This process is recursive, so we always end up with a non-pointer type at the end of the process.

func UnwrapValue

func UnwrapValue(val reflect.Value) reflect.Value

UnwrapValue takes the given reflect.Value, and if it's a pointer gets the pointer element. This process is recursive, so we always end up with a non-pointer type at the end of the process.

func ViolationsToStatus added in v0.1.2

func ViolationsToStatus(violations []ConstraintViolation) *status.Status

ViolationsToStatus returns the given set of constraint violations as a gRPC status.

Types

type Constraint

type Constraint interface {
	Violations(ctx Context) []ConstraintViolation
}

Constraint represents a type that will validate a value and/or adjust the validation scope for further validation (e.g. validating a field on a struct, or an element in a slice).

func LazyDynamic

func LazyDynamic(constraintFn interface{}) Constraint

LazyDynamic is a Constraint that's extremely similar to Lazy, and fulfils mostly the same purpose, but instead expects a function that has a single argument of the type being validated.

type ConstraintFunc

type ConstraintFunc func(ctx Context) []ConstraintViolation

ConstraintFunc provides a convenient way of defining a Constraint as a function instead of a struct, keeping code more compact.

func When

func When(predicate bool, constraints ...Constraint) ConstraintFunc

When conditionally runs some constraints. The predicate is set up at the time of creating the constraints. If you want a more dynamic approach, you should use WhenFn instead. You can also build up constraints programmatically and use the value being validated to build the constraints.

func WhenFn

func WhenFn(predicateFn func(ctx Context) bool, constraints ...Constraint) ConstraintFunc

WhenFn lazily conditionally runs some constraints. The predicate function is called during the validation process. If you need an even more dynamic approach, you can also build up constraints programmatically and use the value being validated to build the constraints.

func (ConstraintFunc) Violations

func (c ConstraintFunc) Violations(ctx Context) []ConstraintViolation

Violations ...

type ConstraintViolation

type ConstraintViolation struct {
	Path     string                 `json:"path"`
	PathKind PathKind               `json:"path_kind"`
	Message  string                 `json:"message"`
	Details  map[string]interface{} `json:"details,omitempty"`
}

ConstraintViolation contains information to highlight a value failing to fulfil the requirements of a Constraint. It contains information to find the value that is failing, and how to resolve the violation.

func ShouldBe

func ShouldBe(ctx Context, typ reflect.Type, kinds ...reflect.Kind) []ConstraintViolation

ShouldBe is the non-panicking alternative to MustBe. Instead of panicking it returns a slice of ConstraintViolation which can be directly returned from a Constraint.

func Validate

func Validate(value interface{}, constraints ...Constraint) []ConstraintViolation

Validate executes the given constraint(s) against the given value, returning any violations of those constraints.

func ValidateContext

func ValidateContext(ctx Context, constraints ...Constraint) []ConstraintViolation

ValidateContext is exactly like Validate, except it doesn't create a Context for you. This allows for more granular configuration provided by the Context type (and means we can avoid creating a Validator struct type to do this).

func ViolationsFromStatus added in v0.2.4

func ViolationsFromStatus(sts *status.Status) []ConstraintViolation

ViolationsFromStatus returns the constraint violations from the given gRPC status. If the status doesn't contain any constraint violations, an empty slice is returned.

type Constraints

type Constraints []Constraint

Constraints is simply a collection of many constraints. All of the constraints will be run, and their results will be aggregated and returned.

func (Constraints) Violations

func (cc Constraints) Violations(ctx Context) []ConstraintViolation

Violations ...

type Context

type Context struct {
	PathKind  PathKind
	StructTag string
	Values    []Value
}

Context contains useful information for a Constraint, including the value(s) being validated.

func NewContext

func NewContext(value interface{}) Context

NewContext returns a new Context, with a Value created for the given interface{} value.

func (*Context) Value

func (c *Context) Value() Value

Value gets the current value (the last value in Values).

func (*Context) Violation

func (c *Context) Violation(message string, details map[string]interface{}) ConstraintViolation

Violation provides a convenient way to produce a ConstraintViolation using the information found on the Context. If a custom violation is needed, one can always be made using the information on the Context manually.

func (Context) WithPathKind

func (c Context) WithPathKind(pathKind PathKind) Context

WithPathKind returns a shallow copy of this Context with the given PathKind assigned, not modifying the original Context.

func (Context) WithValue

func (c Context) WithValue(name string, val reflect.Value) Context

WithValue returns a shallow copy of this Context with the given value assigned, not modifying the original Context.

type Elements

type Elements []Constraint

Elements is a Constraint used to validate every value (element) in an array, a map, or a slice.

func (Elements) Violations

func (e Elements) Violations(ctx Context) []ConstraintViolation

Violations ...

type Fields

type Fields map[string]Constraint

Fields is a Constraint used to validate the values of specific fields on a struct.

func (Fields) Violations

func (f Fields) Violations(ctx Context) []ConstraintViolation

Violations ...

type Keys

type Keys []Constraint

Keys is a Constraint used to validate the keys of a map.

func (Keys) Violations

func (k Keys) Violations(ctx Context) []ConstraintViolation

Violations ...

type Lazy

type Lazy func() Constraint

Lazy is a Constraint that allows a function that returns Constraints to be evaluated at validation-time. This enables things like defining constraints for recursive structures.

func (Lazy) Violations

func (f Lazy) Violations(ctx Context) []ConstraintViolation

Violations ...

type Map

type Map map[interface{}]Constraint

Map is a Constraint used to validate a map. This Constraint validates the values in the map, by specific keys. If you want to use the same validation on all keys of a map, use Elements instead. If you want to validate the keys of the map, use Keys instead.

func (Map) Violations

func (m Map) Violations(ctx Context) []ConstraintViolation

Violations ...

type PathKind

type PathKind int

PathKind enumerates the different possible kinds of values that we validate. This is used to remove the ambiguity in what is being validated in cases where the path could either refer to a key, or a value (e.g. you might want to validate a map's key, but the path to the key would be the same as the path to the value under that key).

const (
	PathKindValue PathKind = iota
	PathKindKey
)

All possible PathKind values.

func (PathKind) MarshalJSON

func (k PathKind) MarshalJSON() ([]byte, error)

MarshalJSON returns a JSON encoded version of the string representation of this PathKind.

func (PathKind) String

func (k PathKind) String() string

String returns the string representation of this PathKind.

func (*PathKind) UnmarshalJSON added in v0.1.13

func (k *PathKind) UnmarshalJSON(bs []byte) error

UnmarshalJSON takes the given bytes and attempts to mutate this PathKind to the appropriate value, if a valid value is given.

type Value

type Value struct {
	Name string
	Node reflect.Value
}

Value represents a value to be validated, and it's "name" (i.e. something we can use to build up a path to the value).

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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