第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Golang:使用 required_if 標記根據(jù)其封閉結構字段之一的值驗證內(nèi)部結構字段

Golang:使用 required_if 標記根據(jù)其封閉結構字段之一的值驗證內(nèi)部結構字段

Go
慕姐4208626 2023-01-03 16:20:11
高朗版本:1.18.3驗證器:github.com/go-playground/validator/v10我想在加載到嵌套結構數(shù)據(jù)結構后驗證傳入的 JSON 有效負載。這是我傳入的 JSON 負載, {        "irn": 1,        "firstName": "Testing",        "lastName": "Test",        "cardType": "RECIPROCAL",        "number": "2248974514",        "cardExpiry": {            "month": "01",            "year": "2025"        }}這是我的 medicare.go 文件 package mainimport (    "encoding/json"    "github.com/go-playground/validator/v10")type Medicare struct {    IRN           uint8    FirstName     string    MiddleInitial string    LastName      string    CardType      string `validate:"required,eq=RESIDENT|eq=RECIPROCAL|eq=INTERIM"`    Number        string    CardExpiry    *CardExpiry `validate:"required"`}type CardExpiry struct {    Day   string    Month string `validate:"required"`    Year  string `validate:"required"`}這是我的測試功能    func TestUserPayload(t *testing.T) {    var m Medicare    err := json.Unmarshal([]byte(jsonData), &m)    if err != nil {        panic(err)    }    validate := validator.New()    err = validate.Struct(m)    if err != nil {        t.Errorf("error %v", err)    }}我想使用 validator/v10 的required_if標記進行以下驗證。這是驗證邏輯,if (m.CardType == "RECIPROCAL" || m.CardType == "INTERIM") &&    m.CardExpiry.Day == "" {    //validation error}required_if可以基于同一結構中的字段值使用(在本例中為 CardExpiry)Day   string `validate:"required_if=Month 01"`我的問題是,可以根據(jù)其封閉結構字段之一(在本例中為 Medicare 結構)的值來完成嗎?例如:Day   string `validate:"required_if=Medicare.CardType RECIPROCAL"`如果可以,怎么做?這是go playground 代碼
查看完整描述

2 回答

?
慕虎7371278

TA貢獻1802條經(jīng)驗 獲得超4個贊

您可以編寫自定義驗證, playground-solution,自定義驗證的文檔可在此處獲得https://pkg.go.dev/github.com/go-playground/validator#CustomTypeFunc



查看完整回答
反對 回復 2023-01-03
?
翻過高山走不出你

TA貢獻1875條經(jīng)驗 獲得超3個贊

有點老的問題,但是 valix ( https://github.com/marrow16/valix ) 可以使用條件“開箱即用”地做這些事情。例子...


package main


import (

    "fmt"

    "net/http"

    "strings"


    "github.com/marrow16/valix"

)


type Medicare struct {

    IRN           uint8  `json:"irn"`

    FirstName     string `json:"firstName"`

    MiddleInitial string `json:"middleInitial"`

    LastName      string `json:"lastName"`

    // set order on this property so that it is evaluated before 'CardExpiry' object is checked...

    // (and set a condition based on its value)

    CardType   string      `json:"cardType" v8n:"order:-1,required,&StringValidToken{['RESIDENT','RECIPROCAL','INTERIM']},&SetConditionFrom{Global:true}"`

    Number     string      `json:"number"`

    CardExpiry *CardExpiry `json:"cardExpiry" v8n:"required,notNull"`

}


type CardExpiry struct {

    // this property is required when a condition of `RECIPROCAL` has been set (and unwanted when that condition has not been set)...

    Day   string `json:"day" v8n:"required:RECIPROCAL,unwanted:!RECIPROCAL"`

    Month string `json:"month" v8n:"required"`

    Year  string `json:"year" v8n:"required"`

}



var medicareValidator = valix.MustCompileValidatorFor(Medicare{}, nil)


func main() {

    jsonData := `{

        "irn": 1,

        "firstName": "Testing",

        "lastName": "Test",

        "cardType": "RECIPROCAL",

        "number": "2248974514",

        "cardExpiry": {

            "month": "01",

            "year": "2025"

        }

    }`


    medicare := &Medicare{}

    ok, violations, _ := medicareValidator.ValidateStringInto(jsonData, medicare)

    // should fail with 1 violation...

    fmt.Printf("First ok?: %v\n", ok)

    for i, v := range violations {

        fmt.Printf("Violation[%d]: Message:%s, Property:%s, Path:%s\n", i+1, v.Message, v.Property, v.Path)

    }


    jsonData = `{

            "irn": 1,

            "firstName": "Testing",

            "lastName": "Test",

            "cardType": "RECIPROCAL",

            "number": "2248974514",

            "cardExpiry": {

                "day": "01",

                "month": "01",

                "year": "2025"

            }

        }`

    ok, _, _ = medicareValidator.ValidateStringInto(jsonData, medicare)

    // should be ok...

    fmt.Printf("Second ok?: %v\n", ok)


    jsonData = `{

            "irn": 1,

            "firstName": "Testing",

            "lastName": "Test",

            "cardType": "INTERIM",

            "number": "2248974514",

            "cardExpiry": {

                "month": "01",

                "year": "2025"

            }

        }`

    ok, _, _ = medicareValidator.ValidateStringInto(jsonData, medicare)

    // should be ok...

    fmt.Printf("Third ok?: %v\n", ok)


    jsonData = `{

            "irn": 1,

            "firstName": "Testing",

            "lastName": "Test",

            "cardType": "INTERIM",

            "number": "2248974514",

            "cardExpiry": {

                "day": "01",

                "month": "01",

                "year": "2025"

            }

        }`

    ok, violations, _ = medicareValidator.ValidateStringInto(jsonData, medicare)

    fmt.Printf("Fourth ok?: %v\n", ok)

    for i, v := range violations {

        fmt.Printf("Violation[%d]: Message:%s, Property:%s, Path:%s\n", i+1, v.Message, v.Property, v.Path)

    }


    // or validate directly from a http request...

    req, _ := http.NewRequest("POST", "", strings.NewReader(jsonData))

    ok, violations, _ = medicareValidator.RequestValidateInto(req, medicare)

    fmt.Printf("Fourth (as http.Request) ok?: %v\n", ok)

    for i, v := range violations {

        fmt.Printf("Violation[%d]: Message:%s, Property:%s, Path:%s\n", i+1, v.Message, v.Property, v.Path)

    }

}

游樂場_


查看完整回答
反對 回復 2023-01-03
  • 2 回答
  • 0 關注
  • 823 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號