validator icon indicating copy to clipboard operation
validator copied to clipboard

Extracting values associated with a tag when validating a struct

Open akib-maredia opened this issue 3 years ago • 1 comments

  • [-] I have looked at the documentation here first?
  • [-] I have looked at the examples provided that may showcase my question here?

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
        },
}

akib-maredia avatar Jun 30 '22 18:06 akib-maredia

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

ngchwanlii-bestsell avatar Aug 02 '22 04:08 ngchwanlii-bestsell