go-playground / validator

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

Dive, Required_If Combination Issue #1190

Closed nishanthrk closed 8 months ago

nishanthrk commented 8 months ago

Package version eg. v9, v10:

Package Version: v10

Issue, Question or Enhancement:

When I trying to run the below code. i get this error this is wired

Output Validation error: Key: 'Application.Applicants[0].Entity.Name' Error:Field validation for 'Name' failed on the 'required' tag Key: 'Application.Applicants[0].Entity.TaxID' Error:Field validation for 'TaxID' failed on the 'required' tag Key: 'Application.Applicants[1].Person.Name' Error:Field validation for 'Name' failed on the 'required' tag Key: 'Application.Applicants[1].Person.Age' Error:Field validation for 'Age' failed on the 'required' tag Key: 'Application.Applicants[1].Person.Email' Error:Field validation for 'Email' failed on the 'required' tag

Code sample, to showcase or reproduce:

package main

import (
    "fmt"
    "github.com/go-playground/validator/v10"
)

type Application struct {
    Applicants []Applicant `validate:"dive"`
}

type Applicant struct {
    ApplicantCategory string `validate:"required,oneof=PERSON ENTITY"`
    Person            Person `validate:"required_if=ApplicantCategory PERSON"`
    Entity            Entity `validate:"required_if=ApplicantCategory ENTITY"`
}

type Person struct {
    Name  string `validate:"required"`
    Age   int    `validate:"required,gte=18"`
    Email string `validate:"required,email"`
}

type Entity struct {
    Name  string `validate:"required"`
    TaxID string `validate:"required"`
}

func main() {
    // Create a new validator instance
    v := validator.New()

    // Create an instance of Application to validate
    data := Application{
        Applicants: []Applicant{
            {
                ApplicantCategory: "PERSON",
                Person: Person{
                    Name:  "John Doe",
                    Age:   25,
                    Email: "john@example.com",
                },
            },
            {
                ApplicantCategory: "ENTITY",
                Entity: Entity{
                    Name:  "Example Corp",
                    TaxID: "123456789",
                },
            },
        },
    }

    // Use the validator to validate the Application struct and its Applicants
    if err := v.Struct(data); err != nil {
        fmt.Println("Validation error:", err)
    } else {
        fmt.Println("Validation passed")
    }
}
nishanthrk commented 8 months ago

@deankarn Need your help in this

florianrusch commented 1 week ago

@nishanthrk did you found a solution? I'm running into the same problem.