Field rules#
FieldRules encapsulates the rules for each type of field. Depending on the field, the correct set should be used to ensure proper validations.
cel#
cel
is a repeated field used to represent a textual expression
in the Common Expression Language (CEL) syntax. For more information,
see our documentation.
message MyMessage {
// The field `value` must be greater than 42.
optional int32 value = 1 [(buf.validate.field).cel = {
id: "my_message.value",
message: "value must be greater than 42",
expression: "this > 42",
}];
}
required#
If required
is true, the field must be set. A validation error is returned
if the field is not set.
syntax="proto3";
message FieldsWithPresence {
// Requires any string to be set, including the empty string.
optional string link = 1 [
(buf.validate.field).required = true
];
// Requires true or false to be set.
optional bool disabled = 2 [
(buf.validate.field).required = true
];
// Requires a message to be set, including the empty message.
SomeMessage msg = 4 [
(buf.validate.field).required = true
];
}
All fields in the example above track presence. By default, Protovalidate
ignores rules on those fields if no value is set. required
ensures that
the fields are set and valid.
Fields that don't track presence are always validated by Protovalidate,
whether they are set or not. It is not necessary to add required
:
syntax="proto3";
message FieldsWithoutPresence {
// `string.email` always applies, even to an empty string.
string link = 1 [
(buf.validate.field).string.email = true
];
// `repeated.min_items` always applies, even to an empty list.
repeated string labels = 4 [
(buf.validate.field).repeated.min_items = 1
];
}
To learn which fields track presence, see the Field Presence cheat sheet.
Note: While field rules can be applied to repeated items, map keys, and map
values, the elements are always considered to be set. Consequently,
specifying repeated.items.required
is redundant.
ignore#
Ignore validation rules on the field if its value matches the specified
criteria. See the Ignore
enum for details.