Skip to content

Instantly share code, notes, and snippets.

@mmitou
Created August 2, 2020 08:55
Show Gist options
  • Select an option

  • Save mmitou/12238faec82bd0f66abe5d71b3b42e89 to your computer and use it in GitHub Desktop.

Select an option

Save mmitou/12238faec82bd0f66abe5d71b3b42e89 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"github.com/go-playground/validator/v10"
)
type Foo struct {
// ID string `validate:"alphanum,len=3|len=5,excludesall=abcdefghijklmnopgrstuvwxyz"`
ID string `validate:"id"`
}
func main() {
validate := validator.New()
validate.RegisterAlias("id", "alphanum,len=3|len=5,excludesall=abcdefghijklmnopgrstuvwxyz")
foo := &Foo{"1ABc2"}
err := validate.Struct(foo)
if err == nil {
panic("expects err is NOT nil")
}
_, ok := err.(*validator.InvalidValidationError)
if ok {
panic("expects ok is false")
}
for _, err := range err.(validator.ValidationErrors) {
fmt.Println(err.Namespace())
fmt.Println(err.Field())
fmt.Println(err.StructNamespace())
fmt.Println(err.StructField())
fmt.Println(err.Tag())
fmt.Println(err.ActualTag())
fmt.Println(err.Kind())
fmt.Println(err.Type())
fmt.Println(err.Value())
fmt.Println(err.Param())
fmt.Println()
}
foo = &Foo{"1ABC2"}
err = validate.Struct(foo)
if err != nil {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment