Skip to content

required_without and excluded_with issues with nested structs #1325

Open
@dakojohn

Description

@dakojohn
  • I have looked at the documentation here first?
  • I have looked at the examples provided that may showcase my question here?

Package version eg. v9, v10:

v10

Issue, Question or Enhancement:

I am working on some code and trying to make two structs XOR'd with each other. As I understand the validations, I should be able to use required_without and excluded_with to make this happen, but they don't seem to do anything?

Code sample, to showcase or reproduce:

package main

import (
	"fmt"

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

// OuterStruct structure will hold either the A or the B struct, but not both.
type OuterStruct struct {
	// these validate tags are basically an XOR between A and B
	A A `validate:"required_without=B,excluded_with=B"`
	B B `validate:"required_without=A,excluded_with=A"`
}

// A structure holds a URL.
type A struct {
	MyString string
}

// B structure holds a string.
type B struct {
	MyOtherString string
}

var a = A{
	MyString: "test",
}

var b = B{
	MyOtherString: "123abcd",
}

func main() {
	v := validator.New()

	fmt.Println("Neither set: should fail")
	fmt.Println(v.Struct(&OuterStruct{A: A{}, B: B{}})) // should fail on required_without

	fmt.Println("Only A set: should pass")
	fmt.Println(v.Struct(&OuterStruct{A: a, B: B{}})) // should pass

	fmt.Println("Only B set: should pass")
	fmt.Println(v.Struct(&OuterStruct{A: A{}, B: b})) // should pass

	fmt.Println("Both set: should fail")
	fmt.Println(v.Struct(&OuterStruct{A: a, B: b})) // should fail on excluded_with
}

Output:

Neither set: should fail
<nil>
Only A set: should pass
<nil>
Only B set: should pass
<nil>
Both set: should fail
<nil>

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions