Skip to content

[Bug]: required_if with multiple values on the same field unexpected behavior #1466

@duyquang6

Description

@duyquang6

What happened?

When using required_if with the same field and multiple comparison values, the validator unexpectedly passes, it should expect error

Example:

type Request struct {
    Type  string `validate:"required"`
    Value string `validate:"required_if=Type A Type B"`
}

Type value cannot be A and B at the same time, so the validator will pass in anycase

Minimal Repro (failing test)

package demo

import (
    "testing"

    "github.com/go-playground/validator/v10"
    "github.com/stretchr/testify/require"
)

type Request struct {
    Type  string `validate:"required"`
    Value string `validate:"required_if=Type A Type B"`
}

func TestValidateRequiredIf(t *testing.T) {
    v := validator.New()

    // Type A, Value empty -> should fire panic error
    r := Request{Type: "A", Value: ""}
    err := v.Struct(r)
    require.Error(t, err, "expected error: Value must be required when Type is A or B")

    // Type B, Value empty -> should fire panic error
    r = Request{Type: "B", Value: ""}
    err = v.Struct(r)
    require.Error(t, err, "expected error: Value must be required when Type is A or B")
}

Expected behavior

This tag validate:"required_if=Type A Type B" should output panic error, and only accept unique field name

Actual behavior

Validation passes (no error) in the above cases

If this makes sense, I’d be happy to help contribute an implementation

Version

v10.12.0

If this makes sense, I’d be happy to help contribute fix

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions