wip
This commit is contained in:
56
mangezmieux-backend/internal/validator/validator.go
Normal file
56
mangezmieux-backend/internal/validator/validator.go
Normal file
@@ -0,0 +1,56 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user