bufbuild / protovalidate

Protocol Buffer Validation - Go, Java, Python, and C++ Beta Releases!
https://buf.build/bufbuild/protovalidate
Apache License 2.0
849 stars 37 forks source link

[Question] validate a repeated field by looping over it #242

Closed rishabh2a closed 3 weeks ago

rishabh2a commented 3 weeks ago

Suppose, my proto file is:

message Interval {
    google.protobuf.Timestamp start_timestamp = 1;
    google.protobuf.Timestamp end_timestamp = 2;
}

message IntervalValues {
    message IntervalValue {
        Interval interval = 1;
        String value = 2;
    }
    repeated IntervalValue interval_values = 1;
}

I want to validate that intervals should be monotonically increasing and the start time of the next interval should be the end time of the previous interval. Is it possible? I couldn't find an example of it.

If I write a code for it, it'll be the following:

for (int i = 1; i < msg.intervalValues.size(); i ++) {
    IntervalValue prevValue = msg.intervalValues.get(i-1);
     IntervalValue currentValue = msg.intervalValues.get(i);

   if (currentValue.getInterval().getStartTime() != prevValue.getInterval().getEndTime()) {
        throw ValidationFailedException()
    }
}
rodaine commented 3 weeks ago

Hi @rishabh2a! CEL expressions do not support loop operations of this kind currently. Take a look at the builtin macros for what's possible in a custom constraint.