Skip to content

Deimvis/validatorsd

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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

  1. 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
    }
  2. (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)
    }
  3. 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 and ValidateSelf methods on structs and substructs
  • Validate 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 by Validate 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]) && ..., because validate called on slice ignores nil entries, but validate called directly on struct returns an error if struct is nil.

About

Extension for validator v10 package

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages