@bufbuilding/protovalidate (英语)
质子化 提供标准说明,以验证关于消息和字段的共同规则,以及使用 简历 写自定义规则。 这是下一代 原型验证,是Protobuf唯一被广泛使用的验证库.
通过Protovalidate,您可以使用标准验证规则和自定义验证规则来注释您的Protobuf消息:
syntax = "proto3";
package banking.v1;
import "buf/validate/validate.proto";
message MoneyTransfer {
string to_account_id = 1 [
// Standard rule: `to_account_id` must be a UUID.
(buf.validate.field).string.uuid = true
];
string from_account_id = 2 [
// Standard rule: `from_account_id` must be a UUID.
(buf.validate.field).string.uuid = true
];
// Custom rule: `to_account_id` and `from_account_id` can't be the same.
option (buf.validate.message).cel = {
id: "to_account_id.not.from_account_id"
message: "to_account_id and from_account_id should not be the same value"
expression: "this.to_account_id != this.from_account_id"
};
}
一旦你加进来 @bufbuild/protovalidate 对于您的项目,验证很简单:
import { create } from "@bufbuild/protobuf";
import { createValidator } from "@bufbuild/protovalidate";
import { MoneyTransferSchema } from "./gen/banking_pb";
const transfer = create(MoneyTransferSchema);
const validator = createValidator();
const result = validator.validate(MoneyTransferSchema, transfer);
if (result.kind !== "valid") {
// Handle failure.
}
[注]
此版本兼容 buf. 建设/建设/开发 页:1
它需要Protobuf运行时间 @ bufbuilding/ protobuf。 。 。 .