feat(binding): Add support for custom validation tags

This commit is contained in:
Suhas Karanth 2017-08-16 08:50:58 +05:30
parent 030b1aaf72
commit fb426562bb
2 changed files with 15 additions and 1 deletions

View File

@ -4,7 +4,11 @@
package binding package binding
import "net/http" import (
"net/http"
validator "gopkg.in/go-playground/validator.v8"
)
const ( const (
MIMEJSON = "application/json" MIMEJSON = "application/json"
@ -31,6 +35,11 @@ type StructValidator interface {
// If the struct is not valid or the validation itself fails, a descriptive error should be returned. // If the struct is not valid or the validation itself fails, a descriptive error should be returned.
// Otherwise nil must be returned. // Otherwise nil must be returned.
ValidateStruct(interface{}) error ValidateStruct(interface{}) error
// RegisterValidation adds a validation Func to a Validate's map of validators denoted by the key
// NOTE: if the key already exists, the previous validation function will be replaced.
// NOTE: this method is not thread-safe it is intended that these all be registered prior to any validation
RegisterValidation(string, validator.Func) error
} }
var Validator StructValidator = &defaultValidator{} var Validator StructValidator = &defaultValidator{}

View File

@ -28,6 +28,11 @@ func (v *defaultValidator) ValidateStruct(obj interface{}) error {
return nil return nil
} }
func (v *defaultValidator) RegisterValidation(key string, fn validator.Func) error {
v.lazyinit()
return v.validate.RegisterValidation(key, fn)
}
func (v *defaultValidator) lazyinit() { func (v *defaultValidator) lazyinit() {
v.once.Do(func() { v.once.Do(func() {
config := &validator.Config{TagName: "binding"} config := &validator.Config{TagName: "binding"}