
vld-rocket
Rocket integration for the vld validation library.
Features
| Extractor |
Source |
Description |
VldJson<T> |
JSON body |
Validates JSON request body |
VldQuery<T> |
Query string |
Validates URL query parameters |
VldForm<T> |
Form body |
Validates application/x-www-form-urlencoded |
All extractors return 422 Unprocessable Entity with a JSON error body on validation failure.
Installation
[dependencies]
vld-rocket = "0.1"
vld = "0.1"
rocket = { version = "0.5", features = ["json"] }
serde_json = "1"
Quick Start
use vld_rocket::prelude::*;
vld::schema! {
#[derive(Debug, Clone)]
pub struct CreateUser {
pub name: String => vld::string().min(2).max(50),
pub email: String => vld::string().email(),
}
}
#[rocket::post("/users", data = "<user>")]
fn create_user(user: VldJson<CreateUser>) -> rocket::serde::json::Json<serde_json::Value> {
rocket::serde::json::Json(serde_json::json!({
"name": user.name,
"email": user.email,
}))
}
#[rocket::main]
async fn main() -> Result<(), rocket::Error> {
rocket::build()
.mount("/", rocket::routes![create_user])
.register("/", rocket::catchers![
vld_rocket::vld_422_catcher,
vld_rocket::vld_400_catcher,
])
.launch()
.await?;
Ok(())
}
Error Catchers
Register the built-in catchers to get JSON error responses:
.register("/", rocket::catchers![
vld_rocket::vld_422_catcher, vld_rocket::vld_400_catcher, ])
Running Examples
cargo run -p vld-rocket --example rocket_basic
Example Requests
curl -X POST http://localhost:8000/users \
-H 'Content-Type: application/json' \
-d '{"name":"Alice","email":"alice@example.com","age":30}'
curl -X POST http://localhost:8000/users \
-H 'Content-Type: application/json' \
-d '{"name":"A","email":"bad","age":-1}'
curl "http://localhost:8000/search?q=hello&page=1&limit=10"
License
MIT