Validaciones con Garde
- Se deben "ejecutar" explícitamente (ver el crate axum-valid que podría validarlo automáticamente)
- Primero se valida la conversión con los tipos primitivos de Rust, por ejemplo
i32,String, etc. - Después, se ejecutan las validaciones con el crate
gardecomo#[garde(email)]
Instalaciones
cargo add garde -F derive,email,url
Structs
use garde::Validate;
use serde::Deserialize;
use time::Date;
#[derive(Deserialize, Validate)]
pub struct CreateAuthorDto {
#[garde(length(min = 2, max = 60))]
pub name: String,
#[garde(email)]
pub email: String,
#[garde(skip)]
pub date_of_birth: Date,
}
Uso
pub async fn create(
State(_db_pool): State<PgPool>,
Json(author): Json<CreateAuthorDto>,
) -> (StatusCode, Json<Value>) {
// Explicit payload validation
if let Err(validation_errors) = author.validate() {
return (
StatusCode::BAD_REQUEST,
Json(serde_json::json!({
"errors": validation_errors.to_string(),
})),
);
}
(
StatusCode::OK,
Json(json!({
"name" : author.name,
"email": author.email,
"date_of_birth": author.date_of_birth
})),
)
}