Module axum_valid::form
source · Expand description
§Support for Form<T>
§Feature
Enable the form
feature (enabled by default) to use Valid<Form<T>>
.
§Usage
- Implement
Deserialize
andValidate
for your data typeT
. - In your handler function, use
Valid<Form<T>>
as some parameter’s type.
§Example
#[cfg(feature = "validator")]
mod validator_example {
use axum::routing::post;
use axum::Form;
use axum::Router;
use axum_valid::Valid;
use serde::Deserialize;
use validator::Validate;
pub fn router() -> Router {
Router::new().route("/form", post(handler))
}
async fn handler(Valid(Form(parameter)): Valid<Form<Parameter>>) {
assert!(parameter.validate().is_ok());
// Support automatic dereferencing
println!("v0 = {}, v1 = {}", parameter.v0, parameter.v1);
}
#[derive(Validate, Deserialize)]
pub struct Parameter {
#[validate(range(min = 5, max = 10))]
pub v0: i32,
#[validate(length(min = 1, max = 10))]
pub v1: String,
}
}
#[cfg(feature = "garde")]
mod garde_example {
use axum::routing::post;
use axum::Form;
use axum::Router;
use axum_valid::Garde;
use serde::Deserialize;
use garde::Validate;
pub fn router() -> Router {
Router::new().route("/form", post(handler))
}
async fn handler(Garde(Form(parameter)): Garde<Form<Parameter>>) {
assert!(parameter.validate(&()).is_ok());
// Support automatic dereferencing
println!("v0 = {}, v1 = {}", parameter.v0, parameter.v1);
}
#[derive(Validate, Deserialize)]
pub struct Parameter {
#[garde(range(min = 5, max = 10))]
pub v0: i32,
#[garde(length(min = 1, max = 10))]
pub v1: String,
}
}