jsval

package module
v0.0.0-...-20277e9 Latest Latest
Warning

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

Go to latest
Published: Dec 5, 2018 License: MIT Imports: 22 Imported by: 0

README

go-jsval

Validator toolset, with code generation from JSON Schema

Build Status

GoDoc

Description

The go-jsval package is a data validation toolset, with a tool to generate validators in Go from JSON schemas.

Synopsis

Read a schema file and create a validator using jsval command:

jsval -s /path/to/schema.json -o validator.go
jsval -s /path/to/hyperschema.json -o validator.go -p "/links/0/schema" -p "/links/1/schema" -p "/links/2/schema"

Read a schema file and create a validator programatically:

package jsval_test

import (
  "log"

  "github.com/lestrrat-go/jsschema"
  "github.com/lestrrat-go/jsval/builder"
)

func ExampleBuild() {
  s, err := schema.ReadFile(`/path/to/schema.json`)
  if err != nil {
    log.Printf("failed to open schema: %s", err)
    return
  }

  b := builder.New()
  v, err := b.Build(s)
  if err != nil {
    log.Printf("failed to build validator: %s", err)
    return
  }

  var input interface{}
  if err := v.Validate(input); err != nil {
    log.Printf("validation failed: %s", err)
    return
  }
}

Build a validator by hand:

func ExampleManual() {
  v := jsval.Object().
    AddProp(`zip`, jsval.String().RegexpString(`^\d{5}$`)).
    AddProp(`address`, jsval.String()).
    AddProp(`name`, jsval.String()).
    AddProp(`phone_number`, jsval.String().RegexpString(`^[\d-]+$`)).
    Required(`zip`, `address`, `name`)

  var input interface{}
  if err := v.Validate(input); err != nil {
    log.Printf("validation failed: %s", err)
    return
  }
}

Install

go get -u github.com/lestrrat-go/jsval

If you want to install the jsval tool, do

go get -u github.com/lestrrat-go/jsval/cmd/jsval

Features

Can generate validators from JSON Schema definition

The following command creates a file named jsval.go which contains various variables containing *jsval.JSVal structures so you can include them in your code:

jsval -s schema.json -o jsval.go

See the file generated_validator_test.go for a sample generated from JSON Schema schema.

If your document isn't a real JSON schema but contains one or more JSON schema (like JSON Hyper Schema) somewhere inside the document, you can use the -p argument to access a specific portion of a JSON document:

jsval -s hyper.json -p "/links/0" -p "/lnks/1"

This will generate a set of validators, with JSON references within the file hyper.json properly resolved.

Can handle JSON References in JSON Schema definitions

Note: Not very well tested. Test cases welcome

This packages tries to handle JSON References properly. For example, in the schema below, "age" input is validated against the positiveInteger schema:

{
  "definitions": {
    "positiveInteger": {
      "type": "integer",
      "minimum": 0,
    }
  },
  "properties": {
    "age": { "$ref": "#/definitions/positiveInteger" }
  }
}

Run a playground server

jsval server -listen :8080

You can specify a JSON schema, and see what kind of validator gets generated.

Tricks

Specifying structs with values that may or may not be initialized

With maps, it's easy to check if a property exists. But if you are validating a struct, however, all of the fields exist all the time, and you basically cannot detect if you have a missing field to apply defaults, etc.

For such cases you should use the Maybe interface provided in this package:

type Foo struct {
  Name MaybeString `json:"name"`
}

This will declare the value as "optional", and the JSVal validation mechanism does the correct thing to process this field.

References

Name Notes
go-jsschema JSON Schema implementation
go-jshschema JSON Hyper Schema implementation
go-jsref JSON Reference implementation
go-jspointer JSON Pointer implementations

Documentation

Overview

Package jsval implements an input validator, based on JSON Schema. The main purpose is to validate JSON Schemas (see https://github.com/lestrrat-go/jsschema), and to automatically generate validators from schemas, but jsval can be used independently of JSON Schema.

Index

Constants

This section is empty.

Variables

View Source
var EmptyConstraint = emptyConstraint{}

EmptyConstraint is a constraint that returns true for any value

View Source
var NullConstraint = nullConstraint{}

NullConstraint is a constraint that only matches the JSON "null" value, or "nil" in golang

Functions

This section is empty.

Types

type AllConstraint

type AllConstraint struct {
	// contains filtered or unexported fields
}

AllConstraint implements a constraint where all of the child constraints' validation must pass in order for this validation to pass.

func All

func All() *AllConstraint

All creates a new AllConstraint

func (*AllConstraint) Add

Add appends a new Constraint

func (*AllConstraint) Constraints

func (c *AllConstraint) Constraints() []Constraint

func (*AllConstraint) Reduce

func (c *AllConstraint) Reduce() Constraint

Reduce returns the child Constraint, if this constraint has only 1 child constraint.

func (*AllConstraint) Validate

func (c *AllConstraint) Validate(v interface{}) (err error)

Validate validates the value against the input value. For AllConstraints, it will only return success if all of the child Constraints succeeded.

type AnyConstraint

type AnyConstraint struct {
	// contains filtered or unexported fields
}

AnyConstraint implements a constraint where at least 1 child constraint must pass in order for this validation to pass.

func Any

func Any() *AnyConstraint

Any creates a new AnyConstraint

func (*AnyConstraint) Add

Add appends a new Constraint

func (*AnyConstraint) Constraints

func (c *AnyConstraint) Constraints() []Constraint

func (*AnyConstraint) Reduce

func (c *AnyConstraint) Reduce() Constraint

Reduce returns the child Constraint, if this constraint has only 1 child constraint.

func (*AnyConstraint) Validate

func (c *AnyConstraint) Validate(v interface{}) (err error)

Validate validates the value against the input value. For AnyConstraints, it will return success the moment one child Constraint succeeds. It will return an error if none of the child Constraints succeeds

type ArrayConstraint

type ArrayConstraint struct {
	// contains filtered or unexported fields
}

ArrayConstraint implements a constraint to match against various aspects of a Array/Slice structure

func Array

func Array() *ArrayConstraint

Array creates a new ArrayConstraint

func (*ArrayConstraint) AdditionalItems

func (c *ArrayConstraint) AdditionalItems(ac Constraint) *ArrayConstraint

AdditionalItems specifies the constraint that additional items must be validated against. Note that if you specify `Items` with this constraint, `AdditionalItems` has no effect. This constraint only makes sense when used along side with the `PositionalItems` constraint.

If you want to allow any additional items, pass `EmptyConstraint` to this method. If unspecified, no extra items are allowed.

func (ArrayConstraint) DefaultValue

func (dv ArrayConstraint) DefaultValue() interface{}

func (ArrayConstraint) HasDefault

func (dv ArrayConstraint) HasDefault() bool

func (*ArrayConstraint) Items

Items specifies the constraint that all items in the array must be validated against

func (*ArrayConstraint) MaxItems

func (c *ArrayConstraint) MaxItems(i int) *ArrayConstraint

MaxItems specifies the maximum number of items in the value. If unspecified, the check is not performed.

func (*ArrayConstraint) MinItems

func (c *ArrayConstraint) MinItems(i int) *ArrayConstraint

MinItems specifies the minimum number of items in the value. If unspecified, the check is not performed.

func (*ArrayConstraint) PositionalItems

func (c *ArrayConstraint) PositionalItems(ac []Constraint) *ArrayConstraint

PositionalItems specifies the constraint that elements in each position of the array being validated. Extra items in the array are validated against the constraint specified for `AdditionalItems`.

func (*ArrayConstraint) UniqueItems

func (c *ArrayConstraint) UniqueItems(b bool) *ArrayConstraint

UniqueItems specifies if the array can hold non-unique items. When set to true, the validation will fail unless all of your elements are unique.

Caveat: Currently we stringify the elements before comparing for uniqueness. This could/should be fixed.

func (*ArrayConstraint) Validate

func (c *ArrayConstraint) Validate(v interface{}) (err error)

Validate validates the given value against this Constraint

type BooleanConstraint

type BooleanConstraint struct {
	// contains filtered or unexported fields
}

BooleanConstraint implements a constraint to match against a boolean.

func Boolean

func Boolean() *BooleanConstraint

Boolean creates a new BooleanConsraint

func (*BooleanConstraint) Default

func (bc *BooleanConstraint) Default(v interface{}) *BooleanConstraint

Default specifies the default value to apply

func (BooleanConstraint) DefaultValue

func (dv BooleanConstraint) DefaultValue() interface{}

func (BooleanConstraint) HasDefault

func (dv BooleanConstraint) HasDefault() bool

func (*BooleanConstraint) Validate

func (bc *BooleanConstraint) Validate(v interface{}) error

Validate vaidates the value against the given value

type Constraint

type Constraint interface {
	DefaultValue() interface{}
	HasDefault() bool
	Validate(interface{}) error
}

Constraint is an object that know how to validate individual types of input

type ConstraintMap

type ConstraintMap struct {
	// contains filtered or unexported fields
}

ConstraintMap is an implementation of RefResolver

func (*ConstraintMap) GetReference

func (cm *ConstraintMap) GetReference(name string) (Constraint, error)

GetReference fetches the Constraint associated with the given name

func (ConstraintMap) Len

func (cm ConstraintMap) Len() int

Len returns the number of references stored in this ConstraintMap

func (*ConstraintMap) SetReference

func (cm *ConstraintMap) SetReference(name string, c Constraint)

SetReference registeres a new Constraint to a name

type EnumConstraint

type EnumConstraint struct {
	// contains filtered or unexported fields
}

EnumConstraint implements a constraint where the incoming value must match one of the values enumerated in the constraint. Note that due to various language specific reasons, you should only use simple types where the "==" operator can distinguish between different values

func Enum

func Enum(v ...interface{}) *EnumConstraint

Enum creates a new EnumConstraint

func (EnumConstraint) DefaultValue

func (nc EnumConstraint) DefaultValue() interface{}

func (*EnumConstraint) Enum

func (c *EnumConstraint) Enum(v ...interface{}) *EnumConstraint

Enum method sets the possible enumerations

func (EnumConstraint) HasDefault

func (nc EnumConstraint) HasDefault() bool

func (*EnumConstraint) Validate

func (c *EnumConstraint) Validate(v interface{}) (err error)

Validate validates the value against the list of enumerations

type ErrInvalidMaybeValue

type ErrInvalidMaybeValue struct {
	Value interface{}
}

func (ErrInvalidMaybeValue) Error

func (e ErrInvalidMaybeValue) Error() string

type Generator

type Generator struct{}

Generator is responsible for generating Go code that sets up a validator

func NewGenerator

func NewGenerator() *Generator

NewGenerator creates a new Generator

func (*Generator) Process

func (g *Generator) Process(out io.Writer, validators ...*JSVal) error

Process takes a validator and prints out Go code to out.

type IntegerConstraint

type IntegerConstraint struct {
	NumberConstraint
}

IntegerConstraint implements a constraint to match against an integer type. Note that after checking if the value is an int (i.e. floor(x) == x), the rest of the logic follows exactly that of NumberConstraint

func Integer

func Integer() *IntegerConstraint

Integer creates a new IntegerrConstraint

func (*IntegerConstraint) Default

func (ic *IntegerConstraint) Default(v interface{}) *IntegerConstraint

Default specifies the default value for the given value

func (IntegerConstraint) DefaultValue

func (dv IntegerConstraint) DefaultValue() interface{}

func (*IntegerConstraint) ExclusiveMaximum

func (ic *IntegerConstraint) ExclusiveMaximum(b bool) *IntegerConstraint

ExclusiveMaximum specifies if the maximum value should be considered a valid value

func (*IntegerConstraint) ExclusiveMinimum

func (ic *IntegerConstraint) ExclusiveMinimum(b bool) *IntegerConstraint

ExclusiveMinimum specifies if the minimum value should be considered a valid value

func (IntegerConstraint) HasDefault

func (dv IntegerConstraint) HasDefault() bool

func (*IntegerConstraint) Maximum

Maximum sepcifies the maximum value that the constraint can allow Maximum sepcifies the maximum value that the constraint can allow

func (*IntegerConstraint) Minimum

Minimum sepcifies the minimum value that the constraint can allow

func (*IntegerConstraint) Validate

func (ic *IntegerConstraint) Validate(v interface{}) (err error)

Validate validates the value against integer validation rules. Note that because when Go decodes JSON it FORCES float64 on numbers, this method will return true even if the *type* of the value is float32/64. We just check that `math.Floor(v) == v`

type JSVal

type JSVal struct {
	*ConstraintMap
	// Name is the name that will be used to generate code for this validator.
	// If unspecified, the generator will create variable names like `V0`, `V1`,
	// `V2`, etc. If you want to generate more meaningful names, you should
	// set this value manually. For example, if you are using jsval with a
	// scaffold generator, you might want to set this to a human-readable value
	Name string
	// contains filtered or unexported fields
}

JSVal is the main validator object.

func New

func New() *JSVal

New creates a new JSVal instance.

func (*JSVal) Root

func (v *JSVal) Root() Constraint

Root returns the root Constraint object.

func (*JSVal) SetConstraintMap

func (v *JSVal) SetConstraintMap(cm *ConstraintMap) *JSVal

SetConstraintMap allows you to set the map that is referred to when resolving JSON references within constraints. By setting this to a common map, for example, you can share the same references to save you some memory space and sanity. See an example in the `generated_validator_test.go` file.

func (*JSVal) SetName

func (v *JSVal) SetName(s string) *JSVal

SetName sets the name for the validator

func (*JSVal) SetRoot

func (v *JSVal) SetRoot(c Constraint) *JSVal

SetRoot sets the root Constraint object.

func (*JSVal) Validate

func (v *JSVal) Validate(x interface{}) error

Validate validates the input, and return an error if any of the validations fail

type JSValSlice

type JSValSlice []*JSVal

JSValSlice is a list of JSVal validators. This exists in order to define methods to satisfy the `sort.Interface` interface

func (JSValSlice) Len

func (p JSValSlice) Len() int

func (JSValSlice) Less

func (p JSValSlice) Less(i, j int) bool

func (JSValSlice) Swap

func (p JSValSlice) Swap(i, j int)

type Maybe

type Maybe interface {
	// Valid should return true if this value has been properly initialized.
	// If this returns false, JSVal will treat as if the field is has not been
	// provided at all.
	Valid() bool

	// Value should return whatever the underlying value is.
	Value() interface{}

	// Set sets a value to this Maybe value, and turns on the Valid flag.
	// An error may be returned if the value could not be set (e.g.
	// you provided a value with the wrong type)
	Set(interface{}) error

	// Reset clears the Maybe value, and sets the Valid flag to false.
	Reset()
}

Maybe is an interface that can be used for struct fields which want to differentiate between initialized and uninitialized state. For example, a string field, if uninitialized, will contain the zero value of "", but that empty string *could* be a valid value for our validation purposes.

To differentiate between an uninitialized string and an empty string, you should wrap it with a wrapper that implements the Maybe interface and JSVal will do its best to figure this out

type MaybeBool

type MaybeBool struct {
	ValidFlag
	Bool bool
}

func (MaybeBool) MarshalJSON

func (v MaybeBool) MarshalJSON() ([]byte, error)

func (*MaybeBool) Set

func (v *MaybeBool) Set(x interface{}) error

func (*MaybeBool) UnmarshalJSON

func (v *MaybeBool) UnmarshalJSON(data []byte) error

func (MaybeBool) Value

func (v MaybeBool) Value() interface{}

type MaybeFloat

type MaybeFloat struct {
	ValidFlag
	Float float64
}

func (MaybeFloat) MarshalJSON

func (v MaybeFloat) MarshalJSON() ([]byte, error)

func (*MaybeFloat) Set

func (v *MaybeFloat) Set(x interface{}) error

func (*MaybeFloat) UnmarshalJSON

func (v *MaybeFloat) UnmarshalJSON(data []byte) error

func (MaybeFloat) Value

func (v MaybeFloat) Value() interface{}

type MaybeInt

type MaybeInt struct {
	ValidFlag
	Int int64
}

func (MaybeInt) MarshalJSON

func (v MaybeInt) MarshalJSON() ([]byte, error)

func (*MaybeInt) Set

func (v *MaybeInt) Set(x interface{}) error

func (*MaybeInt) UnmarshalJSON

func (v *MaybeInt) UnmarshalJSON(data []byte) error

func (MaybeInt) Value

func (v MaybeInt) Value() interface{}

type MaybeString

type MaybeString struct {
	ValidFlag
	String string
}

func (MaybeString) MarshalJSON

func (v MaybeString) MarshalJSON() ([]byte, error)

func (*MaybeString) Set

func (v *MaybeString) Set(x interface{}) error

func (*MaybeString) UnmarshalJSON

func (v *MaybeString) UnmarshalJSON(data []byte) error

func (MaybeString) Value

func (v MaybeString) Value() interface{}

type MaybeTime

type MaybeTime struct {
	ValidFlag
	Time time.Time
}

func (MaybeTime) MarshalJSON

func (v MaybeTime) MarshalJSON() ([]byte, error)

func (*MaybeTime) Set

func (v *MaybeTime) Set(x interface{}) error

func (*MaybeTime) UnmarshalJSON

func (v *MaybeTime) UnmarshalJSON(data []byte) error

func (MaybeTime) Value

func (v MaybeTime) Value() interface{}

type MaybeUint

type MaybeUint struct {
	ValidFlag
	Uint uint64
}

func (MaybeUint) MarshalJSON

func (v MaybeUint) MarshalJSON() ([]byte, error)

func (*MaybeUint) Set

func (v *MaybeUint) Set(x interface{}) error

func (*MaybeUint) UnmarshalJSON

func (v *MaybeUint) UnmarshalJSON(data []byte) error

func (MaybeUint) Value

func (v MaybeUint) Value() interface{}

type NotConstraint

type NotConstraint struct {
	// contains filtered or unexported fields
}

NotConstraint implements a constraint where the result of child constraint is negated -- that is, validation passes only if the child constraint fails.

func Not

func Not(c Constraint) *NotConstraint

Not creates a new NotConstraint. You must pass in the child constraint to be run

func (NotConstraint) DefaultValue

func (nc NotConstraint) DefaultValue() interface{}

DefaultValue is a no op for this constraint

func (NotConstraint) HasDefault

func (nc NotConstraint) HasDefault() bool

HasDefault is a no op for this constraint

func (NotConstraint) Validate

func (nc NotConstraint) Validate(v interface{}) (err error)

Validate runs the validation, and returns an error unless the child constraint fails

type NumberConstraint

type NumberConstraint struct {
	// contains filtered or unexported fields
}

NumberConstraint implements a constraint to match against a number (i.e. float) type.

func Number

func Number() *NumberConstraint

Number creates a new NumberConstraint

func (*NumberConstraint) Default

func (nc *NumberConstraint) Default(v interface{}) *NumberConstraint

Default specifies the default value for the given value

func (NumberConstraint) DefaultValue

func (dv NumberConstraint) DefaultValue() interface{}

func (*NumberConstraint) Enum

func (nc *NumberConstraint) Enum(l ...interface{}) *NumberConstraint

Enum specifies the values that this constraint can have

func (*NumberConstraint) ExclusiveMaximum

func (nc *NumberConstraint) ExclusiveMaximum(b bool) *NumberConstraint

ExclusiveMaximum specifies if the maximum value should be considered a valid value

func (*NumberConstraint) ExclusiveMinimum

func (nc *NumberConstraint) ExclusiveMinimum(b bool) *NumberConstraint

ExclusiveMinimum specifies if the minimum value should be considered a valid value

func (NumberConstraint) HasDefault

func (dv NumberConstraint) HasDefault() bool

func (*NumberConstraint) Maximum

func (nc *NumberConstraint) Maximum(n float64) *NumberConstraint

Maximum sepcifies the maximum value that the constraint can allow

func (*NumberConstraint) Minimum

func (nc *NumberConstraint) Minimum(n float64) *NumberConstraint

Minimum sepcifies the minimum value that the constraint can allow

func (*NumberConstraint) MultipleOf

func (nc *NumberConstraint) MultipleOf(n float64) *NumberConstraint

MultipleOf specifies the number that the given value must be divisible by. That is, the constraint will return an error unless the given value satisfies `math.Mod(v, n) == 0`

func (*NumberConstraint) Validate

func (nc *NumberConstraint) Validate(v interface{}) (err error)

Validate validates the value against this constraint

type ObjectConstraint

type ObjectConstraint struct {

	// FieldNameFromName takes a struct wrapped in reflect.Value, and a
	// field name -- in JSON format (i.e. what you specified in your
	// JSON struct tags, or the actual field name). It returns the
	// struct field name to pass to `Value.FieldByName()`. If you do
	// not specify one, DefaultFieldNameFromName will be used.
	FieldNameFromName func(reflect.Value, string) string

	// FieldNamesFromStruct takes a struct wrapped in reflect.Value, and
	// returns the name of all public fields. Note that the returned
	// names will be JSON names, which may not necessarily be the same
	// as the field name. If you do not specify one, DefaultFieldNamesFromStruct
	// will be used
	FieldNamesFromStruct func(reflect.Value) []string
	// contains filtered or unexported fields
}

ObjectConstraint implements a constraint to match against various aspects of a Map-like structure.

func Object

func Object() *ObjectConstraint

Object creates a new ObjectConstraint

func (*ObjectConstraint) AddProp

func (o *ObjectConstraint) AddProp(name string, c Constraint) *ObjectConstraint

AddProp adds constraints for a named property.

func (*ObjectConstraint) AdditionalProperties

func (o *ObjectConstraint) AdditionalProperties(c Constraint) *ObjectConstraint

AdditionalProperties specifies the constraint that additional properties should be validated against.

func (ObjectConstraint) DefaultValue

func (dv ObjectConstraint) DefaultValue() interface{}

func (*ObjectConstraint) GetPropDependencies

func (o *ObjectConstraint) GetPropDependencies(from string) []string

GetPropDependencies returns the list of property names that must be present for given property name `from`

func (*ObjectConstraint) GetSchemaDependency

func (o *ObjectConstraint) GetSchemaDependency(from string) Constraint

GetSchemaDependency returns the Constraint that must be used when the property `from` is present.

func (ObjectConstraint) HasDefault

func (dv ObjectConstraint) HasDefault() bool

func (*ObjectConstraint) IsPropRequired

func (o *ObjectConstraint) IsPropRequired(s string) bool

IsPropRequired returns true if the given name is listed under the required properties

func (*ObjectConstraint) MaxProperties

func (o *ObjectConstraint) MaxProperties(n int) *ObjectConstraint

MaxProperties specifies the maximum number of properties this constraint can allow. If unspecified, it is not checked.

func (*ObjectConstraint) MinProperties

func (o *ObjectConstraint) MinProperties(n int) *ObjectConstraint

MinProperties specifies the minimum number of properties this constraint can allow. If unspecified, it is not checked.

func (*ObjectConstraint) PatternProperties

func (o *ObjectConstraint) PatternProperties(key *regexp.Regexp, c Constraint) *ObjectConstraint

PatternProperties specifies constraints that properties matching this pattern must be validated against. Note that properties listed using `AddProp` takes precedence.

func (*ObjectConstraint) PatternPropertiesString

func (o *ObjectConstraint) PatternPropertiesString(key string, c Constraint) *ObjectConstraint

PatternPropertiesString is the same as PatternProperties, but takes a string representing a regular expression. If the regular expression cannot be compiled, a panic occurs.

func (*ObjectConstraint) PropDependency

func (o *ObjectConstraint) PropDependency(from string, to ...string) *ObjectConstraint

PropDependency specifies properties that must be present when `from` is present.

func (*ObjectConstraint) Required

func (o *ObjectConstraint) Required(l ...string) *ObjectConstraint

Required specifies required property names

func (*ObjectConstraint) SchemaDependency

func (o *ObjectConstraint) SchemaDependency(from string, c Constraint) *ObjectConstraint

SchemaDependency specifies a schema that the value being validated must also satisfy. Note that the "object" is the target that needs to be additionally validated, not the value of the `from` property

func (*ObjectConstraint) Validate

func (o *ObjectConstraint) Validate(v interface{}) (err error)

Validate validates the given value against this ObjectConstraint

type OneOfConstraint

type OneOfConstraint struct {
	// contains filtered or unexported fields
}

OneOfConstraint implements a constraint where only exactly one of the child constraints' validation can pass. If none of the constraints passes, or more than 1 constraint passes, the expressions deemed to have failed.

func OneOf

func OneOf() *OneOfConstraint

OneOf creates a new OneOfConstraint

func (*OneOfConstraint) Add

Add appends a new Constraint

func (*OneOfConstraint) Constraints

func (c *OneOfConstraint) Constraints() []Constraint

func (*OneOfConstraint) Reduce

func (c *OneOfConstraint) Reduce() Constraint

Reduce returns the child Constraint, if this constraint has only 1 child constraint.

func (*OneOfConstraint) Validate

func (c *OneOfConstraint) Validate(v interface{}) (err error)

Validate validates the value against the input value. For OneOfConstraints, it will return success only if exactly 1 child Constraint succeeds.

type PropInfo

type PropInfo struct {
	// Name of the Field that maps to this property
	FieldName string
	// IsMaybe is true if this property implements the Maybe interface
	IsMaybe bool
}

type RefResolver

type RefResolver interface {
	GetReference(string) (Constraint, error)
}

RefResolver is a mandatory object that you must pass to a ReferenceConstraint upon its creation. This is responsible for resolving the reference to an actual constraint.

type ReferenceConstraint

type ReferenceConstraint struct {
	// contains filtered or unexported fields
}

ReferenceConstraint is a constraint where its actual definition is stored elsewhere.

func Reference

func Reference(resolver RefResolver) *ReferenceConstraint

Reference creates a new ReferenceConstraint object

func (*ReferenceConstraint) Default

func (r *ReferenceConstraint) Default(_ interface{})

Default is a no op for this type

func (*ReferenceConstraint) DefaultValue

func (r *ReferenceConstraint) DefaultValue() interface{}

DefaultValue returns the default value from the constraint pointed by the reference

func (*ReferenceConstraint) HasDefault

func (r *ReferenceConstraint) HasDefault() bool

HasDefault returns true if the constraint pointed by the reference has defaults

func (*ReferenceConstraint) RefersTo

RefersTo specifies the reference string that this constraint points to

func (*ReferenceConstraint) Resolved

func (r *ReferenceConstraint) Resolved() (c Constraint, err error)

Resolved returns the Constraint obtained by resolving the reference.

func (*ReferenceConstraint) Validate

func (r *ReferenceConstraint) Validate(v interface{}) (err error)

Validate validates the value against the constraint pointed to by the reference.

type StringConstraint

type StringConstraint struct {
	// contains filtered or unexported fields
}

StringConstraint implements a constraint to match against a string

func String

func String() *StringConstraint

String creates a new StringConstraint. It unfortunately overlaps the `Stringer` interface :/

func (*StringConstraint) Default

func (sc *StringConstraint) Default(v interface{}) *StringConstraint

Default sets the default value for this constraint.

func (StringConstraint) DefaultValue

func (dv StringConstraint) DefaultValue() interface{}

func (*StringConstraint) Enum

func (sc *StringConstraint) Enum(l ...interface{}) *StringConstraint

Enum specifies the enumeration of the possible values

func (*StringConstraint) Format

func (sc *StringConstraint) Format(f string) *StringConstraint

Format specifies the format that passed value must conform to

func (StringConstraint) HasDefault

func (dv StringConstraint) HasDefault() bool

func (*StringConstraint) MaxLength

func (sc *StringConstraint) MaxLength(l int) *StringConstraint

MaxLength specifies the maximum length the passed value can have

func (*StringConstraint) MinLength

func (sc *StringConstraint) MinLength(l int) *StringConstraint

MinLength specifies the minimum length the passed value must have

func (*StringConstraint) Regexp

Regexp specifies the `*regexp.Regexp` object that passed value must conform to

func (*StringConstraint) RegexpString

func (sc *StringConstraint) RegexpString(pat string) *StringConstraint

RegexpString is the same as Regexp method, except this one takes a string and compiles it.

func (*StringConstraint) Validate

func (sc *StringConstraint) Validate(v interface{}) (err error)

Validate runs the validation against the incoming value. Note that StringConstraint does not apply default values to the incoming string value, because the Zero value for string ("") can be a perfectly reasonable value.

The caller is the only person who can determine if a string value is "unavailable"

type StructInfo

type StructInfo struct {
	// contains filtered or unexported fields
}

func (*StructInfo) FieldName

func (si *StructInfo) FieldName(pname string) (string, bool)

func (*StructInfo) PropNames

func (si *StructInfo) PropNames(rv reflect.Value) []string

Gets the list of property names for this particuar instance of a struct. Uninitialized types are not considered, so we remove them depending on the state of this instance of the struct

type StructInfoRegistry

type StructInfoRegistry struct {
	// contains filtered or unexported fields
}

func (*StructInfoRegistry) Lookup

func (r *StructInfoRegistry) Lookup(t reflect.Type) (StructInfo, bool)

func (*StructInfoRegistry) Register

func (r *StructInfoRegistry) Register(t reflect.Type) StructInfo

type ValidFlag

type ValidFlag bool

func (*ValidFlag) Reset

func (v *ValidFlag) Reset()

func (ValidFlag) Valid

func (v ValidFlag) Valid() bool

Directories

Path Synopsis
cmd
internal

Jump to

Keyboard shortcuts

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