validator

package module
v0.0.0-...-357a9da Latest Latest
Warning

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

Go to latest
Published: Feb 2, 2021 License: MIT Imports: 9 Imported by: 0

README

Support define multiple validation rules for one struct.

This package is based on https://github.com/go-playground/validator/.

For this User struct:

type User struct {
	Name    string
	Age     int
	Address Address
}

type Address struct {
	IP   string
	Area string
}

And fill it:

user := User{
	Name: "I'm Name",
	Age:  15,
	Address: Address{
		IP:   "8.4.3",
		Area: "earth",
	},
}

We can define the validation rules:

fullRules := []validator.Rule{
	{Field: "Name", Tag: "required,lte=20"},
	{Field: "Age", Tag: "min=20,max=100"},
	{Field: "Address.IP", Tag: "ip"},
}

If we DoRules:

validate := validator.New()
validate.DoRules(user, fullRules)

We can get:

validator.VErrors{
	{Field: "Age", Tag: "min", Param: "20", Message: ""},
	{Field: "Address.IP", Tag: "ip", Param: "", Message: ""},
}

We can also use other validation rules to check the user:

addressRules := []validator.Rule{
	{Field: "Address.IP", Tag: "ipv6"},
	{Field: "Address.Area", Tag: "eq=Sun"},
}

validate.DoRules(user, addressRules)

// get:
//
// validator.VErrors{
//     {Field: "Address.IP", Tag: "ipv6", Param: "", Message: ""},
//     {Field: "Address.Area", Tag: "eq", Param: "Sun", Message: ""},
// }

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsStructZero

func IsStructZero(sIface interface{}) bool

Return true when all fields is zero. sIface must be pointer to struct.

func IsValidationError

func IsValidationError(err error) bool

Types

type Error

type Error struct {
	Field   string
	Tag     string
	Param   string
	Code    string
	Message string
	Err     error
}

type Errors

type Errors []Error

func (Errors) Error

func (ves Errors) Error() string

type MapError

type MapError map[string][]string

func VErrorsToMap

func VErrorsToMap(verrs Errors, templateMap TemplateMap) (MapError, error)

templateMap is a map that mean [tag]template, templateMap will be parsed by go template, you can use ".Tag" and ".Param" variable in the template.

For example, validation tag is "max=100", then tag is "max", param is "100", if template is "is too large, maximum is {{.Param}}", then it will be parsed to "is too large, maximum is 100".

If templateMap is nil, it will use defaultTemplateMap to parse. If not found the tag in the templateMap, it will use defaultTemplateMap to parse for this tag, it mean templateMap will merge to defaultTemplateMap, so you don't worry about missing some tags of the templateMap.

If parse template failed, it will return error.

func (MapError) Error

func (vem MapError) Error() string

type Rule

type Rule struct {
	// Field mean field name of struct, it can be nested.
	// For example "Address.City".
	Field string
	// This tag contains tag and param, use "," to separate multiple tags.
	// For example "required,lte=20".
	Tag     string
	Code    string
	Message string
	Err     error
}

type TemplateMap

type TemplateMap map[string]string

type Validate

type Validate struct {
	GPValidate *validator.Validate
	// contains filtered or unexported fields
}

func New

func New() *Validate

func (*Validate) DoRules

func (v *Validate) DoRules(data interface{}, rules []Rule) (Errors, error)

data should be a struct or a pointer to struct.

if return (nil, nil), it mean no validation error.

If it return (nil, error), you must to solve it. Possible errors: * Invalid Rule.Tag * Invalid Rule.Field * data is not a struct or a pointer to struct

Some custom tags: * zipcode_jp * simple_email

func (*Validate) DoRulesAndToMapError

func (v *Validate) DoRulesAndToMapError(data interface{}, rules []Rule) (MapError, error)

Same as DoRules, run DoRules and VErrorsToMap with custom template. You can use RegisterTemplateMap func to register custom template.

func (*Validate) DoRulesAndToMapErrorWithTagName

func (v *Validate) DoRulesAndToMapErrorWithTagName(data interface{}, rules []Rule, tagName string) (MapError, error)

func (*Validate) DoRulesToProtoError

func (v *Validate) DoRulesToProtoError(data interface{}, rules []Rule) *proto.Error

If no any error, return nil.

func (*Validate) DoRulesToStruct

func (v *Validate) DoRulesToStruct(data interface{}, rules []Rule, toStruct interface{})

TODO toStruct can be pointer to struct. toStruct must be pointer to pointer to struct, and fields must contains all rule.Field and type must be []string.

func (*Validate) DoRulesToStructAndSetNil

func (v *Validate) DoRulesToStructAndSetNil(data interface{}, rules []Rule, toStruct interface{})

toStruct must be pointer to pointer to struct, and fields must contains all rule.Field and type must be []string. If no validation errors, then set toStruct to nil.

func (*Validate) DoRulesWithTagName

func (v *Validate) DoRulesWithTagName(data interface{}, rules []Rule, tagName string) (verrs Errors, err error)

func (*Validate) IsVar

func (v *Validate) IsVar(field interface{}, tag string) bool

It's a proxy function for validate.Var from github.com/go-playground/validator. But it return bool type.

If has some invalid input, it will return false.

func (*Validate) RegisterInclusionValidationParam

func (v *Validate) RegisterInclusionValidationParam(param string, validSlice interface{}) error

RegisterInclusionValidationParam register a param for inclusion validation. validSlice are all valid values for param of the inclusion validation, and it must be slice type.

For example, if you register a "gender" param, then you can use `validate:"inclusion=gender"` validation tag for the struct.

If you use a unregistered inclusion param, then this field of the struct validation always failed.

If you register the same param multiple times, the front will be covered. If param is empty, it will return error.

func (*Validate) RegisterRegexpValidation

func (v *Validate) RegisterRegexpValidation(tag string, regexpString string) error

RegisterRegexpValidation adds a regexp validation with the given tag and regexpString

NOTES: - if the key already exists, the previous validation function will be replaced. - this method is not thread-safe it is intended that these all be registered prior to any validation

func (*Validate) RegisterTemplateMap

func (v *Validate) RegisterTemplateMap(templateMap TemplateMap) error

func (*Validate) RegisterValidation

func (v *Validate) RegisterValidation(tag string, fn func(validator.FieldLevel) bool) error

RegisterValidation adds a validation with the given tag.

NOTES: - if the key already exists, the previous validation function will be replaced. - this method is not thread-safe it is intended that these all be registered prior to any validation

TODO if we use this function, we must import github.com/go-playground/validator, this is not good, because we hope only import this package. To find a better way.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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