57 lines
1.0 KiB
Go
57 lines
1.0 KiB
Go
package validator
|
|
|
|
import (
|
|
"context"
|
|
"reflect"
|
|
"strings"
|
|
|
|
validatorLib "github.com/go-playground/validator/v10"
|
|
)
|
|
|
|
var CustomValidators = map[string]customValidator{
|
|
"enum": {
|
|
Message: "This field should be in: %v",
|
|
Validator: validateEnum,
|
|
},
|
|
"required": {
|
|
Message: "This field is required and cannot be empty",
|
|
},
|
|
}
|
|
|
|
type customValidator struct {
|
|
Message string
|
|
Validator validatorLib.FuncCtx
|
|
}
|
|
|
|
func validateEnum(ctx context.Context, fl validatorLib.FieldLevel) bool {
|
|
for _, v := range strings.Split(fl.Param(), " ") {
|
|
if v == fl.Field().String() {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func newValidator() *validatorLib.Validate {
|
|
va := validatorLib.New()
|
|
|
|
va.RegisterTagNameFunc(func(fld reflect.StructField) string {
|
|
name := strings.SplitN(fld.Tag.Get("json"), ",", 2)
|
|
if len(name) < 1 {
|
|
return ""
|
|
}
|
|
return name[0]
|
|
})
|
|
|
|
for k, v := range CustomValidators {
|
|
if v.Validator != nil {
|
|
err := va.RegisterValidationCtx(k, v.Validator)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
}
|
|
}
|
|
|
|
return va
|
|
}
|