1. gvalid.CheckMap: 用于对Map类型的数据进行校验。
func CheckMap(data map[string]interface{}, rules map[string]interface{}, customMsg ...map[string]string) error
示例:
data := g.Map{
"name": "John Doe",
"email": "john@example.com",
}
rules := g.MapStrStr{
"name": "required|length:1,30",
"email": "required|email",
}
err := gvalid.CheckMap(data, rules)
2. gvalid.CheckStruct: 用于对结构体类型的数据进行校验。
func CheckStruct(data interface{}, rules map[string]interface{}, customMsg ...map[string]string) error
示例:
type User struct {
Name string `v:"required|length:1,30"`
Email string `v:"required|email"`
}
user := User{
Name: "John Doe",
Email: "john@example.com",
}
err := gvalid.CheckStruct(user, nil)
3. gvalid.CheckStructDeep: 用于对结构体类型的数据进行深度校验,支持递归校验嵌套结构体。
func CheckStructDeep(data interface{}, rules map[string]interface{}, customMsg ...map[string]string) error
示例:
type User struct {
Name string `v:"required|length:1,30"`
Email string `v:"required|email"`
}
type UserProfile struct {
User User `v:"required"`
NickName string `v:"required|length:1,30"`
}
userProfile := UserProfile{
User: User{Name: "John Doe", Email: "john@example.com"},
NickName: "John",
}
err := gvalid.CheckStructDeep(userProfile, nil)
4. gvalid.CheckStructAssoc: 用于对结构体类型的数据进行关联校验,支持关联字段的校验。
func CheckStructAssoc(data interface{}, assoc map[string]string, customMsg ...map[string]string) error
示例:
type User struct {
Name string `v:"required|length:1,30"`
Email string `v:"required|email"`
}
type UserProfile struct {
User User `v:"required"`
NickName string `v:"required|length:1,30"`
}
userProfile := UserProfile{
User: User{Name: "John Doe", Email: "john@example.com"},
NickName: "John",
}
err := gvalid.CheckStructAssoc(userProfile, g.MapStrStr{"User": "required"})
5. gvalid.CheckMapAssoc: 用于对Map类型的数据进行关联校验,支持关联字段的校验。
func CheckMapAssoc(data map[string]interface{}, assoc map[string]string, customMsg ...map[string]string) error
示例:
data := g.Map{
"user": g.Map{
"name": "John Doe",
"email": "john@example.com",
},
"nickName": "John",
}
assoc := g.MapStrStr{"user": "required"}
err := gvalid.CheckMapAssoc(data, assoc)
这些方法提供了灵活且强大的数据校验功能,你可以根据实际需求选择合适的方法,并结合各种验证规则进行数据校验。自定义规则、错误信息等功能也为你提供了更多的扩展性。
转载请注明出处:http://www.zyzy.cn/article/detail/7591/GoFrame