2 回答

TA貢獻(xiàn)1860條經(jīng)驗(yàn) 獲得超9個(gè)贊
與omitempty一起使用oneof使驗(yàn)證程序庫忽略空值或未設(shè)置的值。
type User struct {
Name string `validate:"required"`
Gender string `validate:"required,oneof=MALE FEMALE"`
Tier *uint8 `validate:"required,eq=0|eq=1|eq=2|eq=3"`
MobileNumber string `validate:"required"`
Email string
Address *Address `validate:"required"`
Children []Child `validate:"required,dive"`
IsEmployed *bool `validate:"required"`
PreferredContactMethod string `validate:"omitempty,oneof=EMAIL PHONE POST SMS"`
RequestedAt time.Time `validate:"required"`
}

TA貢獻(xiàn)1874條經(jīng)驗(yàn) 獲得超12個(gè)贊
使用https://github.com/marrow16/valix ( https://pkg.go.dev/github.com/marrow16/valix ) 可以通過以下方式實(shí)現(xiàn):
package main
import (
"fmt"
"time"
"github.com/marrow16/valix"
)
type User struct {
Name string `json:"name" v8n:"required, notNull"`
Gender string `json:"gender" v8n:"required, notNull, &strtoken{['MALE','FEMALE']}"`
Tier uint8 `json:"tier" v8n:"required, notNull, &mini{0}, &maxi{3}"`
DateOfBirth string `json:"dateOfBirth" v8n:"notNull, &strisod"`
MobileNumber string `json:"mobileNumber" v8n:"required, notNull, &strpatt{'^([0-9]{8,16})$'}"`
Email string `json:"email" v8n:"notNull"`
Address Address `json:"address" v8n:"required, notNull"`
Children []Child `json:"children" v8n:"required, notNull"`
IsEmployed bool `json:"isEmployed" v8n:"required"`
PreferredContactMethod string `json:"preferredContactMethod" v8n:"notNull, &strtoken{['EMAIL','PHONE','POST','SMS']}"`
RequestedAt time.Time `json:"requestedAt" v8n:"required, notNull, &strisodt"`
}
type Address struct {
City string `json:"city" v8n:"required, notNull"`
Street string `json:"street" v8n:"required, notNull"`
}
type Child struct {
Title string `json:"title" v8n:"required, notNull"`
FirstName string `json:"firstName" v8n:"notNull"`
LastName string `json:"lastName" v8n:"required, notNull"`
}
const jsonData = `{
"name": "Duro",
"gender": "MALE",
"tier": 3,
"dateOfBirth": "2000-01-13",
"mobileNumber": "0356874586",
"address": {
"city": "Tokyo",
"street": "Shibaura St"
},
"children":[
{
"title": "Mr",
"lastName": "Takayashi"
}
],
"isEmployed": false,
"requestedAt": "2022-01-10T03:30:12.639Z"
}`
var UserRequestValidator = valix.MustCompileValidatorFor(User{}, nil)
func main() {
user := User{}
ok, violations, _ := UserRequestValidator.ValidateStringInto(jsonData, &user)
if ok {
fmt.Println("Validation successful")
} else {
fmt.Println(fmt.Sprintf("Validation failed! (violations: %d)", len(violations)))
for _, v := range violations {
fmt.Printf("%s (property: '%s', path: '%s')\n", v.Message, v.Property, v.Path)
}
}
}
在這里去游樂場:https ://go.dev/play/p/3zrkZx97m-e
披露:我是 Valix 的作者
- 2 回答
- 0 關(guān)注
- 181 瀏覽
添加回答
舉報(bào)