go-playground / validator

:100:Go Struct and Field validation, including Cross Field, Cross Struct, Map, Slice and Array diving
MIT License
16.83k stars 1.32k forks source link

Extracting values associated with a tag when validating a struct #970

Open akib-maredia opened 2 years ago

akib-maredia commented 2 years ago

v9

Issue, Question or Enhancement:

I am using validator with baked in tags and need the tag values to override an existing function. eg for tag min=1, I want to extract 1. Can someone provide some thoughts on this? I tried checking multiple functions provided by FieldLevel interface but none of them provide me the value I am looking for.

Code sample, to showcase or reproduce:


type Name struct {
    FamilyName string `json:"familyName,omitempty" validate:"required,min=1,max=255"`
    GivenName  string `json:"givenName,omitempty" validate:"required,min=1,max=255"`
}

// inside validate.go we register custom translator

{
    tag: "min",
    customRegisFunc: func(ut ut.Translator) error {
        return ut.Add("min", "'{0}' does not satisfy minimum length requirements. ", true)
    },
    customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
        t, _ := ut.T("min", fe.Field())
        return t
    },
    customValidFunc: func(fl validator.FieldLevel) bool {
        if input, ok := fl.Field().Interface().(string); ok {
            param := fl.Param()
            size := fl.Field()
            name := fl.FieldName()
            tag := fl.GetTag()
            value, kind, _ := fl.ExtractType(fl.Field())
            if len(strings.TrimSpace(input)) < {value from tag i.e min=1 hence 1} {
                return false
            }
             }
        return true
        },
}
ngchwanlii-bestsell commented 2 years ago

Looking for the same use case too. Any updates on this?