go-playground / validator

:100:Go Struct and Field validation, including Cross Field, Cross Struct, Map, Slice and Array diving
MIT License
16.64k stars 1.32k forks source link

how to validate inner slice item use required_if? #1210

Open Orocker opened 8 months ago

Orocker commented 8 months ago

Package version v10:

v10.14.0

Issue, Question or Enhancement:

Now expecting validation to fail because of discount_type=discount outside

Code sample, to showcase or reproduce:

https://go.dev/play/p/N4JEKaJQDSe

package main

import (
    "fmt"

    "github.com/go-playground/validator/v10"
)

type StorePromotion struct {
    BatchStair   []StairItem `json:"batch_stair" validate:"required,dive"`
    DiscountType string      `json:"discount_type" validate:"required,oneof=amount discount"`
}

type StairItem struct {
    SubjectNum int8  `json:"subject_num" validate:"required"`
    Value      int64 `json:"value" validate:"required"`
    Limit      int64 `json:"limit" validate:"required_if=DiscountType discount"` # It doesn't work
}

func main() {
    validate := validator.New()
    s := &StorePromotion{
        DiscountType: "discount",
        BatchStair: []StairItem{
            {SubjectNum: 1, Value: 100, Limit: 100},
            {SubjectNum: 2, Value: 90},
            {SubjectNum: 3, Value: 80},
        },
    }
    err := validate.Struct(s)
    fmt.Println(err)
}