this is my struct:
type User struct {
Name `validate:"custom_validation"`
}
this is my custom validation:
func customFunc(fl validator.FieldLevel) bool {
// I want to get struct name inside here
// do some validations...
return true
}
validate.RegisterValidation("custom_validation", customFunc)
the reason is I need to do some check to the database, I need the table name for that, therefore I need the struct name, because the table name is similar to the struct name. If I hard-coded the table name this customFunc
cannot be used to validate in other struct.
How can I do that?
ref: https://pkg.go.dev/github.com/go-playground/validator/v10#hdr-Custom_Validation_Functions
CodePudding user response:
Simple
Get name of the field:
fl.FieldName()
Get value of the field:
fl.Field().String()
Get struct type:
fl.Parent().Type().String()