英文:
How to add validator tag to a nested field
问题
这是我的代码:
type AbstractAccount struct {
Email string `gorm:"unique;type:varchar"`
PasswordHash string `gorm:"unique;type:varchar"`
}
type Planner struct {
AbstractAccount
}
我想通过Planner
为Email
添加一个自定义验证器标签,例如:
type Planner struct {
AbstractAccount `validator:"Email:customTag"`
}
在Go Validator中有没有一种方法可以实现这个,或者有没有任何库可以实现这个?
英文:
Here is my code
type AbstractAccount struct {
Email string `gorm:"unique;type:varchar"`
PasswordHash string `gorm:"unique;type:varchar"`
}
type Planner struct {
AbstractAccount
}
I want to add a custom validator tag to Email
through Planner
for example
type Planner struct {
AbstractAccount `validator:"Email:customTag"`
}
Is there a way to to it in go validator, or is there any library to do it?
答案1
得分: 2
示例程序
在这个示例程序中,有一个名为getFieldsWithCustomTag的函数,它以反射值作为参数,并递归地搜索带有标签c-tag:true(你可以更改这个标签)的字段。它将这些字段追加到一个切片中,并且如果遇到嵌套结构体,它会递归调用自身来搜索嵌套结构体中的字段。
英文:
Sample program
inside that sample program there is a function called getFieldsWithCustomTag it takes a reflect value as an argument and recursively searches for fields with the tag c-tag:true(you can change this). It appends these fields to a slice and, if a nested struct is encountered, recursively calls itself to search for fields in the nested struct.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论