Gin: Custom validator function

Created on 13 Jun 2016  路  7Comments  路  Source: gin-gonic/gin

Hi I wonder if there is a way to write custom validator function as straight usage of v8 provides (gin use it for validation while binding, right? https://godoc.org/gopkg.in/go-playground/validator.v8)

Or is there a way to overwrite a validator used by gin??

Most helpful comment

Tried reinstallinng gopkg.in/go-playground/validator.v8. Also fetched master branch of gin but still facing same issue.

github.com/vbmade2000/contacti/vendor/github.com/gin-gonic/gin/binding
vendor/github.com/gin-gonic/gin/binding/default_validator.go:38:14: undefined: validator.Config
vendor/github.com/gin-gonic/gin/binding/default_validator.go:39:29: too many arguments in call to validator.New

All 7 comments

If I remember correctly, you can specify your own validator object. Can't test it right now, but it should be something like:

gin.Validator = &myObj

But at the same time, you should be able to use all the features of v8 as you normally would with the default implementation. It's quite flexible.

Hello again.
gin.Validator = validator.New(validator.Config{TagName: "binding"})

Doesn't work

I can use all v8 features apart from adding custom validator as it require access to validate structure.

Found it!

import val "gopkg.in/go-playground/validator.v8"

func main() {
binding.Validator = &Validator{val.New(&val.Config{TagName: "validate"})}
engine := gin.Default()
}

type Validator struct {
*val.Validate
}

func (v *Validator) ValidateStruct(i interface{}) error {
return v.Struct(i)
}

github.com/gin-gonic/gin/binding

binding/default_validator.go:29: undefined: validator.Config
binding/default_validator.go:30: too many arguments in call to validator.New
have ()
want ()

@lijinya Current gin use v8.18.1 of gopkg.in/go-playground/validator.v8, u may fix it by reinstall this package

Tried reinstallinng gopkg.in/go-playground/validator.v8. Also fetched master branch of gin but still facing same issue.

github.com/vbmade2000/contacti/vendor/github.com/gin-gonic/gin/binding
vendor/github.com/gin-gonic/gin/binding/default_validator.go:38:14: undefined: validator.Config
vendor/github.com/gin-gonic/gin/binding/default_validator.go:39:29: too many arguments in call to validator.New

It seems the gopkg.in/go-playground/validator.v9 is download when to get gin. I got one way to solve it through glide. And set glide.yaml as below

- package: gopkg.in/go-playground/validator.v8
  version: ~8.18.1
- package: github.com/gin-gonic/gin
  version: ^1.2.0
- package: github.com/gin-contrib/sse
Was this page helpful?
0 / 5 - 0 ratings

Related issues

boneq picture boneq  路  3Comments

sofish picture sofish  路  3Comments

oryband picture oryband  路  3Comments

wangcn picture wangcn  路  3Comments

rawoke083 picture rawoke083  路  3Comments