validator

package module
v1.4.1 Latest Latest
Warning

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

Go to latest
Published: May 20, 2019 License: MIT Imports: 10 Imported by: 0

README

go-validator

GoDoc Reference CircleCI codecov Go Report Card GitHub release

go-validator is a data validation library for Go.

Installation

go get -u github.com/utahta/go-validator

Benchmarks

3.2 GHz Intel Core i7, 64 GB 2667 MHz DDR4

goos: darwin
goarch: amd64
pkg: github.com/utahta/go-validator
BenchmarkValidateVarSuccess-12                          30000000                58.0 ns/op             0 B/op          0 allocs/op
BenchmarkValidateVarParallelSuccess-12                  100000000               12.3 ns/op             0 B/op          0 allocs/op
BenchmarkValidateStructSuccess-12                       10000000               184 ns/op               0 B/op          0 allocs/op
BenchmarkValidateStructParallelSuccess-12               50000000                37.1 ns/op             0 B/op          0 allocs/op
BenchmarkValidateStructComplexSuccess-12                 1000000              1112 ns/op              32 B/op          3 allocs/op
BenchmarkValidateStructComplexParallelSuccess-12        10000000               222 ns/op              32 B/op          3 allocs/op
BenchmarkValidateVarFailure-12                          10000000               187 ns/op             224 B/op          3 allocs/op
BenchmarkValidateStructComplexFailure-12                  500000              3740 ns/op            3760 B/op         60 allocs/op
BenchmarkValidateStructComplexParallelFailure-12         1000000              1117 ns/op            3760 B/op         60 allocs/op

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func ValidateStruct

func ValidateStruct(s interface{}) error

ValidateStruct validates a struct that uses the struct field's tag using default validator.

Example (Or)
type user struct {
	ID string `valid:"or(alpha|numeric)"`
}

v := validator.New()
err := v.ValidateStruct(&user{
	ID: "abc",
})
fmt.Println(err)

err = v.ValidateStruct(&user{
	ID: "123",
})
fmt.Println(err)

err = v.ValidateStruct(&user{
	ID: "abc123",
})
fmt.Println(err)
Output:

<nil>
<nil>
ID: 'abc123' does validate as 'or(alpha|numeric)'
Example (SetFunc)
type content struct {
	Type string `valid:"contentType(image/jpeg|image/png|image/gif)"`
}

v := validator.New(
	validator.WithFunc("contentType", func(_ context.Context, f validator.Field, opt validator.FuncOption) (bool, error) {
		v := f.Value().String()
		for _, param := range opt.TagParams {
			if v == param {
				return true, nil
			}
		}
		return false, nil
	}),
)
err := v.ValidateStruct(&content{
	Type: "image/jpeg",
})
fmt.Println(err)

err = v.ValidateStruct(&content{
	Type: "image/bmp",
})
fmt.Println(err)
Output:

<nil>
Type: 'image/bmp' does validate as 'contentType(image/jpeg|image/png|image/gif)'
Example (Simple)
type user struct {
	Name  string `valid:"required,alphanum"`
	Age   uint   `valid:"required,len(0|116)"`
	Email string `valid:"optional,email"`
}

v := validator.New()
err := v.ValidateStruct(&user{
	Name:  "gopher",
	Age:   9,
	Email: "",
})
fmt.Println(err)

err = v.ValidateStruct(&user{
	Name:  "_",
	Age:   200,
	Email: "invalid",
})
fmt.Println(err)
Output:

<nil>
Name: '_' does validate as 'alphanum';Age: '200' does validate as 'len(0|116)';Email: 'invalid' does validate as 'email'

func ValidateStructContext

func ValidateStructContext(ctx context.Context, s interface{}) error

ValidateStructContext validates a struct that uses the struct field's tag using default validator. Pass context to each validating functions.

func ValidateVar

func ValidateVar(s interface{}, rawTag string) error

ValidateVar validates a value using default validator.

func ValidateVarContext

func ValidateVarContext(ctx context.Context, s interface{}, rawTag string) error

ValidateVarContext validates a value using default validator. Pass context to each validating functions.

Types

type Adapter

type Adapter func(Func) Func

Adapter is a validating function adapter.

type Error

type Error interface {
	// Field returns a validating field.
	Field() Field

	// Tag returns a validation tag.
	Tag() Tag

	// Error returns an error message string.
	Error() string
}

Error is an interface that represents a validation error

type Errors

type Errors []Error

Errors represents validation errors

func ToErrors

func ToErrors(err error) (Errors, bool)

ToErrors converts an error to the validation Errors.

func (Errors) Error

func (es Errors) Error() string

type Field

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

Field represents a value.

func (Field) Interface

func (f Field) Interface() interface{}

Interface returns an interface{}

func (Field) Name

func (f Field) Name() string

Name is a field name. e.g. Foo.Bar.Value

func (Field) Parent

func (f Field) Parent() ParentField

Parent returns a parent field.

func (Field) ShortString

func (f Field) ShortString() string

ShortString returns a string with 32 characters or more omitted.

func (Field) String

func (f Field) String() string

String returns a string.

func (Field) Value

func (f Field) Value() reflect.Value

Value returns a current field value.

type Func

type Func func(context.Context, Field, FuncOption) (bool, error)

Func is the type of validating function.

type FuncMap

type FuncMap map[string]Func

FuncMap is the type of map of validating functions.

type FuncOption

type FuncOption struct {
	// TagParams represents the validation tag parameters.
	// e.g. len(1|2) -> []string{"1", "2"}
	TagParams []string
	// contains filtered or unexported fields
}

FuncOption is the argument of validating function.

type Option

type Option func(v *Validator)

func WithAdapters

func WithAdapters(adapters ...Adapter) Option

WithAdapters is a validator option that sets validator function adapters.

func WithFunc

func WithFunc(k string, fn Func) Option

WithFunc is a validator option that sets a validating function.

func WithFuncMap

func WithFuncMap(funcMap FuncMap) Option

WithFuncMap is a validator option that sets validating functions.

func WithSuppressErrorFieldValue

func WithSuppressErrorFieldValue() Option

WithSuppressErrorFieldValue is a validator option that enables suppress validating field value by error. If enabled this option, the field value always replaces `The value`.

func WithTagKey

func WithTagKey(k string) Option

WithTagKey is a validator option that sets the key in the struct field's tag.

type ParentField

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

ParentField represents a parent of Field.

func (ParentField) Interface

func (f ParentField) Interface() interface{}

Interface returns an interface{}

type Tag

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

Tag represents the validation tag in struct field's tag.

func (Tag) Fullname

func (t Tag) Fullname() string

Fullname returns a tag value.

func (Tag) String

func (t Tag) String() string

String returns a tag value.

type Validator

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

Validator is a validator that validates each fields using struct field's tag.

func DefaultValidator

func DefaultValidator() *Validator

DefaultValidator returns a default validator.

func New

func New(opts ...Option) *Validator

New returns a Validator

func (*Validator) Apply

func (v *Validator) Apply(opts ...Option)

Apply applies validator options.

func (*Validator) ValidateStruct

func (v *Validator) ValidateStruct(s interface{}) error

ValidateStruct validates a struct that uses the struct field's tag.

func (*Validator) ValidateStructContext

func (v *Validator) ValidateStructContext(ctx context.Context, s interface{}) error

ValidateStructContext validates a struct that uses the struct field's tag. Pass context to each validating functions.

func (*Validator) ValidateVar

func (v *Validator) ValidateVar(s interface{}, rawTag string) error

ValidateVar validates a value.

func (*Validator) ValidateVarContext

func (v *Validator) ValidateVarContext(ctx context.Context, s interface{}, rawTag string) error

ValidateVarContext validates a value. Pass context to each validating functions.

Jump to

Keyboard shortcuts

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