go-ozzo / ozzo-validation

An idiomatic Go (golang) validation package. Supports configurable and extensible validation rules (validators) using normal language constructs instead of error-prone struct tags.
MIT License
3.73k stars 224 forks source link

Problem with validating slice struct fields #25

Closed noonien closed 7 years ago

noonien commented 7 years ago

The following test:

func TestInStruct(t *testing.T) {
    var v struct {
        Field []string
    }
    v.Field = []string{"v1"}

    err := ValidateStruct(&v,
        Field(&v.Field, In("v1", "v2")),
    )
    if err != nil {
        t.Fatal(err)
    }
}

Fails with: Field: must be a valid value.

qiangxue commented 7 years ago

This is expected. The In rule checks if a value can be found in the list of prespecified values. See the code doc below: // Note that the value being checked and the possible range of values must be of the same type.

noonien commented 7 years ago

I see, how does one validate such a case though? Should In() not work with slice types?

qiangxue commented 7 years ago

You are trying to determine if a string slice is "in" another string slice. This is not well defined - should the former be fully included in the latter, or should it allow partial intersection?

You will need to have a custom rule to support this check. You may refer to the in.go file for details. It's not very complicated.

noonien commented 7 years ago

Well, such a field would be valid if all elements in it are valid.

But I understand why creating a new rule makes more sense.