validator icon indicating copy to clipboard operation
validator copied to clipboard

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

Open chargraves85 opened this issue 6 months ago • 0 comments

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

chargraves85 avatar Aug 16 '24 15:08 chargraves85