我正在尝试根据一些标准验证golang结构。我正在使用这个库验证器.v9。我正在使用structException((来排除某些验证。当SessionInfo为零时,我想排除VenueInfoession Info上的验证。同样,我想排除对TicketDetails上所有元素的SessionInfo验证。
示例代码段。
package main
import (
"fmt"
"time"
"gopkg.in/go-playground/validator.v9"
)
type (
// Event model
Event struct {
VenueInfo []VenueDetails `json:"venueInfo,omitempty" validate:"min=1,dive,required"`
}
// TicketDetails model
TicketDetails struct {
TicketTypeName string `json:"ticketTypeName,omitempty" validate:"required"`
}
// SessionDetails model
SessionDetails struct {
ShowTime time.Time `json:"showTime,omitempty" validate:"required"`
TicketInfo []TicketDetails `json:"ticketInfo,omitempty" validate:"required_with_all=ShowTime,min=1,dive"`
}
// VenueDetails model
VenueDetails struct {
VenueName string `json:"venueName,omitempty" validate:"required"`
SessionInfo []SessionDetails `json:"sessionInfo,omitempty" validate:"required_with_all=Name,min=1,dive"`
}
)
func main() {
validate := validator.New()
eventDetails := &Event{
VenueInfo: []VenueDetails{
{
VenueName: "Bengaluru International Exhibition Centre",
SessionInfo: []SessionDetails{
{
ShowTime: time.Now(),
// TicketInfo: []TicketDetails{
// {
// TicketTypeName: "Gold Class",
// },
// },
},
},
},
{
VenueName: "Bengaluru International Exhibition Centre",
SessionInfo: []SessionDetails{
{
ShowTime: time.Now(),
// TicketInfo: []TicketDetails{
// {
// TicketTypeName: "Gold Class",
// },
// },
},
},
},
},
}
// 1st use case : applying excluding validation for VenueInfo
excludeVenueInfo := []string{"VenueInfo"}
if err := validate.StructExcept(eventDetails, excludeVenueInfo...); err != nil {
fmt.Println(err.Error())
} else {
fmt.Println("Success")
}
// 2nd use case : applying excluding validation for SessionInfo & TicketInfo
excludeSessionInfo := []string{"VenueInfo[0].SessionInfo"}
if err := validate.StructExcept(eventDetails, excludeSessionInfo...); err != nil {
fmt.Println(err.Error())
} else {
fmt.Println("Success")
}
// 3rd use case : applying excluding validation for TicketInfo
excludeTicketInfo := []string{"VenueInfo[0].SessionInfo[0].TicketInfo"}
if err := validate.StructExcept(eventDetails, excludeTicketInfo...); err != nil {
fmt.Println(err.Error())
} else {
fmt.Println("Success")
}
}
在验证中使用omiteempty。
package main
import (
"fmt"
"gopkg.in/go-playground/validator.v9"
)
type (
AlienObject struct {
A string `json:"a,omitempty" validate:"omitempty,min=6"`
B string `json:"b,omitempty" validate:"omitempty,min=6"`
}
)
func main() {
validate := validator.New()
h := AlienObject{A:"abcdooii"}
if err := validate.Struct(h); err != nil {
fmt.Println(err.Error())
} else {
fmt.Println("Success")
}
}