如何在自定义验证函数中获取结构体名称

huangapple go评论72阅读模式
英文:

How to get struct name inside custom validation function

问题

这是我的结构体:

type User struct {
  Name `validate:"custom_validation"`
}

这是我的自定义验证函数:

func customFunc(fl validator.FieldLevel) bool {
    // 我想在这里获取结构体名称
    
    // 进行一些验证...
    
    return true
}

validate.RegisterValidation("custom_validation", customFunc)

原因是我需要对数据库进行一些检查,我需要表名,因此我需要结构体名称,因为表名与结构体名称类似。如果我硬编码表名,那么customFunc将无法用于验证其他结构体。

我该如何做到这一点?

参考:https://pkg.go.dev/github.com/go-playground/validator/v10#hdr-Custom_Validation_Functions

英文:

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

答案1

得分: 2

简单

获取字段的名称:

fl.FieldName()

获取字段的值:

fl.Field().String()

获取结构体类型:

fl.Parent().Type().String()

英文:

Simple

Get name of the field:

fl.FieldName()

Get value of the field:

fl.Field().String()

Get struct type:

fl.Parent().Type().String()

huangapple
  • 本文由 发表于 2022年10月26日 09:40:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/74201813.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定