protoc-gen-validate icon indicating copy to clipboard operation
protoc-gen-validate copied to clipboard

More than one rule on a field

Open jon-whit opened this issue 5 years ago • 3 comments

I'd like a validation constraint where a repeated message is both required and has a min_items constraint.

For example, something like this:

message Resource {
    string name = 1;
    string parent = 2;
}

message CreateResourcesRequest {
    repeated Resource resources = 1 [(validate.rules) = {
        message: {required = true},
        repeated: {min_items = 1}
    }];
}

Right now if the resources field is unspecified (e.g. nil) then the iterator over the collection just returns immediately and so no inner validation on the min_items constraint is performed.

How do I do this properly? I can't get anything of this sorts to work.

jon-whit avatar Dec 15 '20 15:12 jon-whit

If I'm understanding your question correctly, the min_items rule will enforce that the field is required (said another way, for a repeated field, min_items: 1 is equivalent to saying it's required).

rodaine avatar Dec 17 '20 19:12 rodaine

@rodaine I'm saying that's what I'd expect the behavior to be. But as it stands, you can have a repeated field with min_items: 1, but if the field is entirely omitted (e.g. field == nil) then that validation constraint is not enforced. Does that make sense?

jon-whit avatar Dec 17 '20 23:12 jon-whit

Hm, this may be a bug in that case. It doesn't appear we have a test covering a nil repeated field with a min/max setting.

rodaine avatar Feb 03 '21 01:02 rodaine