type CoolName struct {
Foo string `json:"foo"`
Bar string `json:"bar"`
}
With the Go validator, I want to make only one of these two fields required and give an error if the content of both fields is full.
I used required_without
but it only helps with requiring one of them. I can't figure out how can i validate if both fields doesn't have a content at the same time.
I've just spent some time fighting this same issue, but I seem to have figured it out:
type CoolName struct {
Foo string `json:"foo" validate:"required_without=Bar,excluded_with=Bar"`
Bar string `json:"bar" validate:"required_without=Foo,excluded_with=Foo"`
}
This does the trick and even makes some sence. However, I find the documentation on _with
/_without
tags a little misleading:
The field under validation must be present and not empty only when any of the other specified fields are not present.
For me this implies that "field must be present <=> (if and only if) other field is not".