/!\ 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.
HttpField
you can validate different fields like cookies, headers, query parameters and parameters.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
The full documentation is available here
simple validation
```rust
// Our own validator is a simple closure to check if the field is a number
fn isnumber(fieldname: &str, fieldvalue: Option<&str>) -> Result<(), String> {
if let Some(fieldvalue) = fieldvalue {
if fieldvalue.parse::
Ok(()) }
//... 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::
// ... your main function ```
// Simply call it on a cookie session
for example:
validatormiddleware.addvalidator(HttpField::Cookie("session"), islengthunder(20));
```