Skip to content

[Bug] required_unless and expected_unless syntax does not work the same way #1306

Open
@chargraves85

Description

@chargraves85

Package version eg. v9, v10:

v10

Issue, Question or Enhancement:

When validating multiple values of a single field using excluded_unless and required_unless the syntax seems to result in different expectations.

See the code sample for a better explanation.

Code sample, to showcase or reproduce:

In this first example, using excluded_unless, all 3 written scenarios throw an error.

package main

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


type TestStruct struct {
	Foo int
	Bar string `validate:"excluded_unless=Foo 1 Foo 2"`
}

func main() {

	validator := validator.New()

	testA := TestStruct{
		Foo: 1,
		Bar: "test",
	}
	testB := TestStruct{
		Foo: 2,
		Bar: "test",
	}
	testC := TestStruct{
		Foo: 3,
		Bar: "test",
	}

	err := validator.Struct(testA)
	if err != nil {
		fmt.Println(err.Error())
	}

	err = validator.Struct(testB)
	if err != nil {
		fmt.Println(err.Error())
	}

	err = validator.Struct(testC)
	if err != nil {
		fmt.Println(err.Error())
	}

}

In this second example, using required_unless, only testC throws an error.

package main

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


type TestStruct struct {
	Foo int
	Bar string `validate:"required_unless=Foo 1 Foo 2"`
}

func main() {

	validator := validator.New()

	testA := TestStruct{
		Foo: 1,
	}
	testB := TestStruct{
		Foo: 2,
	}
	testC := TestStruct{
		Foo: 3,
	}

	err := validator.Struct(testA)
	if err != nil {
		fmt.Println(err.Error())
	}

	err = validator.Struct(testB)
	if err != nil {
		fmt.Println(err.Error())
	}

	err = validator.Struct(testC)
	if err != nil {
		fmt.Println(err.Error())
	}

}

I would expect that either both scenarios would throw errors with all scenarios, or the excluded_unless behaves similarly to the latter, in that only TestC should throw errors.

Suggested Proposal

First, I think we should update the implementations to have similar behavior. Secondly, I think the documentation in general lacks instruction for validating multiple values for a single field. Perhaps the answer is to simply use the OR operator | and redeclare the validation tag, but either way it should be documented.

https://github.com/go-playground/validator/pull/1307/files

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