tide-validator


Crates.io version docs.rs docs

/!\ Currently waiting for a new release of Tide before release this one on crates.io /!\

tide-validator is a middleware working with Tide, a web framework in Rust which let you validate your data coming from a request. You'll be able to create custom validators to validate your HTTP parameters, query parameters, cookies and headers.

Features

Validators

To create your own validator it's just a closure to create with this form:

rust // The first closure's parameter is the parameter/queryparameter/cookie/header name. // The second parameter is the value of this HTTP element. // None means the field doesn't exist in the request (useful to force specific fields to be required). Fn(&str, Option<&str>) -> Result<(), T> + Send + Sync + 'static where T: Serialize + Send + Sync + 'static

Documentation

The full documentation is available here

Examples

//... in main function let mut app = tide::new(); let mut validatormiddleware = ValidatorMiddleware::new(); // 'age' is the parameter name inside the route '/test/:age' validatormiddleware.addvalidator(HttpField::Param("age"), isnumber); // You can assign different middleware for each routes therefore different validators for each routes app.at("/test/:age") .middleware(validatormiddleware) .get(|: tide::Request<()>| async move { let cat = Cat { name: "Gribouille".into(), }; tide::Response::new(StatusCode::Ok).body_json(&cat).unwrap() }); app.listen("127.0.0.1:8080").await?; ```

// ... your main function

let mut app = tide::new(); let mut validatormiddleware = ValidatorMiddleware::new(); // Here 'age' is a query parameter, the validator stay the same as in previous example validatormiddleware.addvalidator(HttpField::QueryParam("age"), isnumber); // You can also add multiple validators on a single query parameter to check different things validatormiddleware.addvalidator(HttpField::QueryParam("age"), is_required);

// You can assign different middleware for each routes therefore different validators for each routes app.at("/test") .middleware(validatormiddleware) .get(|: tide::Request<()>| async move { let cat = Cat { name: "Mozart".into(), }; tide::Response::new(StatusCode::Ok).body_json(&cat).unwrap() }, );

app.listen("127.0.0.1:8080").await?; ```

struct CustomError { status_code: usize, message: String, }

// Your validator can also return your own error type fn isnumber(fieldname: &str, fieldvalue: Option<&str>) -> Result<(), CustomError> { if let Some(fieldvalue) = fieldvalue { if fieldvalue.parse::().iserr() { return Err(CustomError { statuscode: 400, message: format!( "field '{}' = '{}' is not a valid number", fieldname, fieldvalue ), }); } } Ok(()) }

// ... your main function ```

// Simply call it on a cookie session for example: validatormiddleware.addvalidator(HttpField::Cookie("session"), islengthunder(20)); ```

Todo