Crates.io | prost-validate |
lib.rs | prost-validate |
version | 0.2.6 |
source | src |
created_at | 2024-10-09 16:52:38.18975 |
updated_at | 2024-10-16 08:42:47.766612 |
description | protoc-gen-validate's validation for prost |
homepage | |
repository | https://github.com/linka-cloud/prost-validate |
max_upload_size | |
id | 1402605 |
size | 35,932 |
prost-validate
A protobuf library extending prost with validation support.
This is a rust implementation of protoc-gen-validate.
It uses the prost
crate to generate the derive
based validation code.
For a reflection based implementation see the prost-reflect-validate crate.
It must be used with prost generated code.
All validation rules are documented in the proto file or in the protoc-gen-validate documentation.
cargo add prost-validate --features derive
cargo add prost-validate-build --build
Proto definition
proto/message.proto
:
syntax = "proto3";
package validate.example;
import "validate/validate.proto";
message ExampleMessage {
string content = 1 [(validate.rules).string = {const: "Hello, world!"}];
}
Build script
build.rs
:
fn main() -> Result<(), Box<dyn std::error::Error>> {
prost_validate_build::Builder::new()
.compile_protos(&["message.proto"], &["proto", "../prost-validate-types/proto"])?:
Ok(())
}
Validation
include!(concat!(env!("OUT_DIR"), "/validate.example.rs"));
fn main() {
use example_proto::ExampleMessage;
use prost_validate::Validator;
match ExampleMessage::default().validate() {
Ok(_) => println!("Validation passed"),
Err(e) => eprintln!("Validation failed: {}", e),
}
let msg = ExampleMessage {
content: "Hello, world!".to_string(),
};
match msg.validate() {
Ok(_) => println!("Validation passed"),
Err(e) => eprintln!("Validation failed: {}", e),
}
}
Output:
Validation failed: "validate.example.ExampleMessage.content": must be equal to "Hello, world!"
Validation passed