Search code examples
c#protocol-buffersprotobuf-csharp-portproto3

Validate and override defaults during parsing stage


Using C# native package of 3.0.0-beta3 version, as per official documentation defaults are assigned during parsing stage and there is no way to distinguish whether value was not passed at all, for my purposes this is vital point since I wanted to do some kind of validation for decoded proto entities so wondering if anyone has experience with custom validation of data or overriding/intercepting parsing stage in any way?

Some basic examples:

  1. For int32 field in case it was not passed at all so instead of default 0 I want to handle this case and raise custom exception
  2. For int32 field I wanted to enforce allowed value range like 100-1000 otherwise throw parsing exception
  3. For string field I wanted to enforce minimum length on parsing/decoding stage

How would you suggest do this except writing custom validation layer on top of protobuf package/API? I still hope there is an extensibility points but not found yet


Solution

  • Validation needs to be done in the application code post-parsing. There are no hooks to do this in the parser itself.

    Proto3 does not distinguish between default-valued fields and unsent fields. In fact, on the sending end, if the field has been explicitly set to its default value, it won't be encoded. So, there is no way to implement your first rule in proto3.