validate

package module
v1.0.14 Latest Latest
Warning

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

Go to latest
Published: Jun 24, 2023 License: GPL-3.0 Imports: 12 Imported by: 0

README

Validate

Tired of super long long struct tags? Use this instead

Install

go get -u github.com/vinshop/validate

Usage

package main

import (
	. "github.com/vinshop/validate"
	"log"
)

type TestStruct struct {
	A interface{}
	B int64
	C []TestStruct
}

func main() {
	data := TestStruct{
		A: "abcde",
		B: 100,
		C: []TestStruct{
			{
				A: "Hello",
				B: 123,
			},
			{
				A: 123,
				B: 123,
			},
		},
	}

	if err := Use(data, Struct(
		WithKey("some key here"),
		Field("A", Require, MinLength(5)),
		Field("B", Require),
		Field("C", Array(Each(Struct(
			Field("A", String()),
		)))),
	)).Validate(); err != nil {
		log.Fatal(err)
	}
}

Document

Config
SetIncludeErrPath(value bool)
Validator

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrRequired = errors.New("value required")
	ErrMustIn   = func(arr interface{}) error {
		return fmt.Errorf("value must be one of %v", arr)
	}
	ErrNotEqual = func(i interface{}) error {
		return fmt.Errorf("value must be equal to %v", i)
	}
	ErrEqual = func(i interface{}) error {
		return fmt.Errorf("value must not be %v", i)
	}
	ErrNotKind = func(k reflect.Kind) error {
		return fmt.Errorf("value kind must be %v", k.String())
	}
)

Common error

View Source
var (
	ErrNotArray = errors.New("must be an array")
	ErrMinSize  = func(l int) error {
		return fmt.Errorf("size must be equal or greater than %v", l)
	}
	ErrMaxSize = func(l int) error {
		return fmt.Errorf("size must be equal or smaller than %v", l)
	}
)

Array error

View Source
var (
	ErrNotNumber = errors.New("not a number")
	ErrNEQ       = func(n float64) error {
		return fmt.Errorf("must not be equal to %v", n)
	}
	ErrEQ = func(n float64) error {
		return fmt.Errorf("must be equal to %v", n)
	}
	ErrLT = func(n float64) error {
		return fmt.Errorf("must be less than %v", n)
	}
	ErrGT = func(n float64) error {
		return fmt.Errorf("must be greater than %v", n)
	}
	ErrLTE = func(n float64) error {
		return fmt.Errorf("must be equal or less than %v", n)
	}
	ErrGTE = func(n float64) error {
		return fmt.Errorf("must be equal or greater than %v", n)
	}
)
View Source
var (
	ErrNotString = errors.New("must be a string")
	ErrMaxLength = func(l int) error {
		return fmt.Errorf("string length must not be greater than %v", l)
	}
	ErrMinLength = func(l int) error {
		return fmt.Errorf("string length must be greater than %v", l)
	}
	ErrRegexNotMatch = func(regex string) error {
		return fmt.Errorf("string not match regex %v", regex)
	}
	ErrNotURL = errors.New("must be an url")

	ErrNotEmail = errors.New("must be an email address")

	ErrNotUUID = errors.New("string is not a valid UUID")

	ErrNotJSONString = errors.New("must be a json string")
)
View Source
var (
	ErrTime         = errors.New("not a valid date")
	ErrNotInt64     = errors.New("must be int64")
	ErrNoTimeSource = errors.New("time source not chosen")
	ErrBefore       = func(t time.Time) error {
		return fmt.Errorf("time must before %v", t)
	}
	ErrAfter = func(t time.Time) error {
		return fmt.Errorf("time must after %v", t)
	}
)
View Source
var (
	ErrNotStruct = errors.New("must be an object")
)
View Source
var NumberEpsilon = 1e-6

NumberEpsilon we need this because sometime compare 2 float64 could be stupid

Functions

func ArrayError

func ArrayError(index int, err error) error

ArrayError error for Array

func FieldError

func FieldError(key string, field reflect.StructField, err error) error

FieldError error for Field in Struct validator

func IsZero

func IsZero(v interface{}) bool

IsZero check if data is zero or not

func MustBeArray added in v1.0.1

func MustBeArray(data interface{}, fn func(s reflect.Value) error) error

MustBeArray check if data is array, if not return ErrNotArray

func MustBeInt64 added in v1.0.5

func MustBeInt64(data interface{}, fn func(i int64) error) error

MustBeInt64 check if data is int64, if not return ErrNotInt64

func MustBeNumber added in v1.0.5

func MustBeNumber(data interface{}, fn func(a float64) error) error

MustBeNumber check if data is Number, if not return ErrNotNumber

func MustBeRegex added in v1.0.1

func MustBeRegex(data string, fn func(r *regexp.Regexp) error) error

MustBeRegex check if data is regexp.Regexp, if not return err

func MustBeString added in v1.0.1

func MustBeString(data interface{}, fn func(s string) error) error

MustBeString check if data is String, if not return ErrNotString

func MustBeStruct added in v1.0.1

func MustBeStruct(data interface{}, fn func(data reflect.Value) error) error

MustBeStruct check if data is a struct, if not return ErrNotStruct

func MustBeTime added in v1.0.5

func MustBeTime(data interface{}, fn func(t time.Time) error) error

MustBeTime check if data is time.Time, if not return ErrTime

func SetIncludeErrPath added in v1.0.13

func SetIncludeErrPath(value bool)

SetIncludeErrPath set true if you want the error message include the full path globally

func SetNumberEpsilon added in v1.0.7

func SetNumberEpsilon(eps float64)

Types

type ArrayFn

type ArrayFn func(v *ArrayValidate)

ArrayFn Array function

func ArrayHas

func ArrayHas(fns ...Rule) ArrayFn

ArrayHas check array info of array like MinSize, MaxSize, etc...

func Each

func Each(fns ...Rule) ArrayFn

Each check each element in array

type ArrayValidate

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

ArrayValidate validator for array

func (ArrayValidate) Do

func (a ArrayValidate) Do(data interface{}) error

type BoolFunc added in v1.0.11

type BoolFunc func() bool

BoolFunc function return boolean value, to make sure it's not panic

type Conditional

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

Conditional condition validator

func If

func If(ok ...BoolFunc) *Conditional

If create new conditional for array, if data is non-zero then return Then, else return Else

func (*Conditional) Do

func (c *Conditional) Do(data interface{}) error

func (*Conditional) Else

func (c *Conditional) Else(fns ...Rule) *Conditional

Else validator if condition is zero

func (*Conditional) Then

func (c *Conditional) Then(fns ...Rule) *Conditional

Then validator if condition is non-zero

type ErrType

type ErrType string
const (
	ErrField    ErrType = "field"
	ErrArrIndex ErrType = "arr_idx"
)

type Error

type Error struct {
	Type ErrType
	Key  string
	Name string
	Err  error
	// contains filtered or unexported fields
}

Error common error type

func (*Error) Error

func (e *Error) Error() string

func (*Error) GetLastErrorWithKey

func (e *Error) GetLastErrorWithKey() error

GetLastErrorWithKey return the last Error has Key

func (*Error) GetRootError

func (e *Error) GetRootError() (string, error)

GetRootError return the root error

func (*Error) IncludePath added in v1.0.14

func (e *Error) IncludePath() *Error

type Keyable

type Keyable interface {
	Key() string
}

Keyable interface for Struct has custom Key

type NumberValidate added in v1.0.5

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

NumberValidate Number validator

func (*NumberValidate) Do added in v1.0.5

func (v *NumberValidate) Do(data interface{}) error

type Rule

type Rule interface {
	Do(data interface{}) error
}

Rule common interface

var Email Rule = RuleFn(func(data interface{}) error {
	return MustBeString(data, func(s string) error {
		if _, err := mail.ParseAddress(s); err != nil {
			return ErrNotEmail
		}
		return nil
	})
})

Email check if string is valid Email using mail.ParseAddress, if not return ErrNotEmail

var JSONString Rule = RuleFn(func(data interface{}) error {
	return MustBeString(data, func(s string) error {
		var js interface{}
		if err := json.Unmarshal([]byte(s), &js); err != nil {
			return ErrNotJSONString
		}
		return nil
	})
})

JSONString check if string is a valid json, if not return ErrNotJSONString

var Require Rule = RuleFn(func(v interface{}) error {
	if IsZero(v) {
		return ErrRequired
	}
	return nil
})

Require check data is empty use IsZero method, if not return ErrRequired

var URL Rule = RuleFn(func(data interface{}) error {
	return MustBeString(data, func(s string) error {
		if _, err := url.ParseRequestURI(s); err != nil {
			return ErrNotURL
		}
		return nil
	})
})

URL check if string is valid URL using url.ParseRequestURI, if not return ErrNotURL

var UUID Rule = RuleFn(func(data interface{}) error {
	return MustBeString(data, func(s string) error {
		if _, err := uuid.Parse(s); err != nil {
			return ErrNotUUID
		}
		return nil
	})
})

UUID check if string is valid UUID using uuid.Parse, if not return ErrNotUUID

func After added in v1.0.5

func After(after time.Time) Rule

After check if data is time instance after given time, if not return ErrAfter

func Array

func Array(fns ...ArrayFn) Rule

Array check if data is array

func Before added in v1.0.5

func Before(before time.Time) Rule

Before check if data is time instance before given time, if not return ErrBefore

func ChangeTime added in v1.0.5

func ChangeTime(fn func(t time.Time) time.Time, fns ...Rule) Rule

ChangeTime modify the data time instance

func CustomNumber added in v1.0.5

func CustomNumber(fn func(n float64) error) Rule

CustomNumber custom validator for number

func DoMath added in v1.0.5

func DoMath(fn func(n float64) float64, fns ...Rule) Rule

DoMath do some math to the number then validate

func EQ added in v1.0.5

func EQ(n float64) Rule

EQ check if number == n, if not return ErrEQ

func Equal added in v1.0.5

func Equal(i interface{}) Rule

Equal check data equal to interface, if not return ErrNotEqual

func GT added in v1.0.5

func GT(n float64) Rule

GT check if number > n, if not return ErrGT

func GTE added in v1.0.5

func GTE(n float64) Rule

GTE check if number >= n, if not return ErrGTE

func In added in v1.0.5

func In(arr interface{}) Rule

In check data is an element in array, if not return ErrMustIn

func IsKind added in v1.0.5

func IsKind(kind reflect.Kind) Rule

IsKind check data kind is given kind,if not return ErrNotKind

func LT added in v1.0.5

func LT(n float64) Rule

LT check if number < n, if not return ErrLT

func LTE added in v1.0.5

func LTE(n float64) Rule

LTE check if number <= n, if not return ErrLTE

func Match

func Match(regex string) Rule

Match check if string match regex, if not return ErrRegexNotMatch

func MaxLength

func MaxLength(l int) Rule

MaxLength check if string has max length of l, if not return ErrMaxLength

func MaxSize

func MaxSize(l int) Rule

MaxSize check array has length <= l, if not return ErrMaxSize.

func MinLength

func MinLength(l int) Rule

MinLength check if string has min length of l, if not return ErrMinLength

func MinSize

func MinSize(l int) Rule

MinSize check array has length >= l, if not return ErrMinSize

func NEQ added in v1.0.5

func NEQ(n float64) Rule

NEQ check if number != n, if not return ErrNEQ

func NotEqual added in v1.0.5

func NotEqual(i interface{}) Rule

NotEqual check data equal to interface, if equal return ErrNotEqual

func Number added in v1.0.5

func Number(fns ...Rule) Rule

Number create new Number validator

func Optional added in v1.0.5

func Optional(fns ...Rule) Rule

Optional only validate if data is not empty

func String

func String(fns ...Rule) Rule

String create new StringValidate

func StringCustom

func StringCustom(fn func(s string) error) Rule

StringCustom custom string validator

func Struct

func Struct(fns ...StructFn) Rule

Struct create new StructValidator

type RuleFn

type RuleFn func(data interface{}) error

RuleFn rule as func

func (RuleFn) Do

func (v RuleFn) Do(data interface{}) error

Do execute the logic

type Rules

type Rules []Rule

Rules array of Rule

func (Rules) Do

func (r Rules) Do(data interface{}) error

type StringValidate

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

StringValidate validator for String

func (StringValidate) Validate

func (s StringValidate) Validate() error

type StructFn

type StructFn func(v *StructValidator)

StructFn Struct function

func Field

func Field(name string, fns ...Rule) StructFn

Field validator for Field

func WithKey

func WithKey(key string) StructFn

WithKey custom key instead of field name or json tag

type StructValidator

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

StructValidator validate for Struct

func (*StructValidator) Do

func (v *StructValidator) Do(data interface{}) error

type SwitchCase

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

SwitchCase switch case validator

func Switch

func Switch() *SwitchCase

Switch create SwitchCase validator

func (*SwitchCase) Case

func (s *SwitchCase) Case(value interface{}, rule ...Rule) *SwitchCase

Case validator if value match case

func (*SwitchCase) CaseCustom added in v1.0.11

func (s *SwitchCase) CaseCustom(ok BoolFunc, rule ...Rule) *SwitchCase

CaseCustom custom validate, has higher priority than Case

func (*SwitchCase) CaseMany

func (s *SwitchCase) CaseMany(value []interface{}, rule ...Rule) *SwitchCase

CaseMany same as Case but take multiple case

func (*SwitchCase) Default

func (s *SwitchCase) Default(rule ...Rule) *SwitchCase

Default if not match any case, return default

func (*SwitchCase) Do

func (s *SwitchCase) Do(data interface{}) error

type TimeValidator added in v1.0.5

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

func Date added in v1.0.5

func Date(layout string, loc *time.Location, fns ...Rule) *TimeValidator

Date parse date from layout string and loc, default layout is time.RFC3339, default loc is time.Local

func Nano added in v1.0.5

func Nano(fns ...Rule) *TimeValidator

Nano parse date from nano

func Second added in v1.0.5

func Second(fns ...Rule) *TimeValidator

Second parse date from second

func (*TimeValidator) Do added in v1.0.5

func (t *TimeValidator) Do(data interface{}) error

type Valid

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

Valid main validator

func Use

func Use(data interface{}, fns ...Rule) *Valid

Use add Rule for data

func (*Valid) Do added in v1.0.1

func (v *Valid) Do(_ interface{}) error

func (*Valid) IncludePath added in v1.0.14

func (v *Valid) IncludePath() *Valid

func (*Valid) Validate

func (v *Valid) Validate() error

type Validatable

type Validatable interface {
	Validate() error
}

type Wrapper added in v1.0.10

type Wrapper struct {
	Data  interface{}
	Type  reflect.Type
	Value reflect.Value
}

func Wrap added in v1.0.10

func Wrap(data interface{}) *Wrapper

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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