Skip to content

Instantly share code, notes, and snippets.

@tranphuoctien
Created February 23, 2018 19:32
Show Gist options
  • Save tranphuoctien/48eb0a184e54ad4a9bcc8ef0535f9748 to your computer and use it in GitHub Desktop.
Save tranphuoctien/48eb0a184e54ad4a9bcc8ef0535f9748 to your computer and use it in GitHub Desktop.
package validation
import (
"fmt"
"reflect"
"strings"
validatorP "gopkg.in/go-playground/validator.v9"
)
// CustomValidator to validate request
type CustomValidator struct {
ValidatorX *validatorP.Validate
}
//NewValidator add more func
func NewValidator() *validatorP.Validate {
validate := validatorP.New()
validate.RegisterTagNameFunc(func(fld reflect.StructField) string {
name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
if name == "-" {
return ""
}
return name
})
return validate
}
//Validate run validate request
func (cv *CustomValidator) Validate(i interface{}) error {
errV := cv.ValidatorX.Struct(i)
if errV != nil {
var tmpErr []string
for _, err := range errV.(validatorP.ValidationErrors) {
tmpErr = append(tmpErr, fmt.Sprintf("Field validation for '%s' failed on the '%s'", err.Field(), err.ActualTag()))
}
return (fmt.Errorf("%s", strings.Join(tmpErr, "\n")))
}
return errV
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment