repositorypackage
0.1.1
Repository: https://github.com/deimvis/validatorsd.git
Documentation: pkg.go.dev
# Packages
No description provided by the author
# README
Validator Simplified package
Validator Simplified is an extension for validator v10 package that allows you to avoid the registration step when adding custom validation to your struct. Instead of writing and registering a separate function, you need to implement a ValidateSelf() error
method in your struct and call the generic Validate
function which will validate the struct using both validation tags and ValidateSelf
methods.
Installation
go get github.com/Deimvis/validatorsd
Quick Start
-
Define your models (structs) + Implement
ValidateSelf
method// models.go package hi import "errors" type MyStruct struct { Answer int } func (s *MyStruct) ValidateSelf() error { if s.Answer != 42 { return errors.New("answer is wrong") } return nil }
-
(optionally) Create a validation shortcut
// validation.go package hi import ( "github.com/Deimvis/validatorsd" "github.com/go-playground/validator/v10" ) var val = validator.New(validator.WithRequiredStructEnabled()) func Validate(obj interface{}) error { return validatorsd.Validate(val, obj) }
-
Validate your model
// main.go package hi import "fmt" func main() { s := MyStruct{ Answer: 99, } err := Validate(s) fmt.Println(err) // answer is wrong }
Details
Validate
function validates using both validation tags andValidateSelf
methods on structs and substructsValidate
returns error when the given object is nil (except when the given object is a slice, it returns nil)Validate
goes recursively through substructs, including embedded structs- If a struct/substruct doesn't implement a
ValidateSelf
method, nothing will happen and it will still be recursively traversed byValidate
function - It doesn't matter whether
ValidateSelf
method has a value or a pointer receiver —Validate
function will find it either way - Slice validation is supported for slice fields, but there are several caveats. For example,
validate(slice)
!=validate(slice[0]) && validate(slice[1]) && ...
, becausevalidate
called on slice ignores nil entries, butvalidate
called directly on struct returns an error if struct is nil.