如何为嵌套字段添加验证器标签

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

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
}

我想通过PlannerEmail添加一个自定义验证器标签,例如:

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.

huangapple
  • 本文由 发表于 2023年5月23日 20:56:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76314997.html
匿名

发表评论

匿名网友

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

确定