Skip to content

How rules apply#

If you add a rule to a field, validation does not necessarily apply.

Fields that do not track presence#

Validation always applies to fields that don't track presence. Even when omitting values for these fields, each field will be validated. For example, all of the fields in this message are always validated, even if no value is provided:

Fields that are always validated in proto3
message User {
  string email = 1 [(buf.validate.field).string.email = true];
  bool verified = 2 [(buf.validate.field).bool.const = true];
  repeated string terms = 3 [(buf.validate.field).repeated.min_items = 1];
  map<string, int32> scores = 4 [(buf.validate.field).map.min_pairs = 1];
}

Fields that track presence#

Fields that track presence behave differently; rules only apply if the field is set.

(In proto3, only message fields, members of a Protobuf oneof, and fields with the optional label track presence.)

For a simple example, consider the following field with the optional label:

Field that is only validated if set
message User {
  optional string email = 1 [(buf.validate.field).string.email = true];
}

For this optional field, rules only apply if the field is set. Similarly, rules on fields in a oneof only apply to the field that is set. Because message fields always track presence, rules only apply if a message is set.

To ensure that a field is set, you can use the required rule. It's typically used for message fields:

Require a field to be set
message Order {
  User user = 1 [(buf.validate.field).required = true];
}

Note that field presence changes with proto2, and with Editions. To learn which fields track presence, see the Field Presence cheat sheet.