pub struct Validated<T>(pub T);Expand description
Wraps a T: FromRequest + Validate, extracting and validating in one step.
Returns 422 Unprocessable Entity with a JSON error body if validation
fails, or the upstream extraction error (typically 400) if extraction fails.
§Example
use rust_web_server::validate::{Validate, Validated, ValidationErrors};
use rust_web_server::extract::{FromRequest, BodyText};
use rust_web_server::core::New;
use rust_web_server::request::Request;
use rust_web_server::response::Response;
struct Name(String);
impl FromRequest for Name {
fn from_request(req: &Request) -> Result<Self, Response> {
let BodyText(s) = BodyText::from_request(req)?;
Ok(Name(s))
}
}
impl Validate for Name {
fn validate(&self) -> Result<(), ValidationErrors> {
let mut errors = ValidationErrors::new();
if self.0.is_empty() { errors.add("name", "must not be empty"); }
if errors.is_empty() { Ok(()) } else { Err(errors) }
}
}
fn handle(req: &Request) -> Response {
let Validated(name) = match Validated::<Name>::from_request(req) {
Ok(v) => v,
Err(res) => return res, // 400 or 422
};
Response::new()
}Tuple Fields§
§0: TTrait Implementations§
Source§impl<T: FromRequest + Validate> FromRequest for Validated<T>
impl<T: FromRequest + Validate> FromRequest for Validated<T>
Auto Trait Implementations§
impl<T> Freeze for Validated<T>where
T: Freeze,
impl<T> RefUnwindSafe for Validated<T>where
T: RefUnwindSafe,
impl<T> Send for Validated<T>where
T: Send,
impl<T> Sync for Validated<T>where
T: Sync,
impl<T> Unpin for Validated<T>where
T: Unpin,
impl<T> UnsafeUnpin for Validated<T>where
T: UnsafeUnpin,
impl<T> UnwindSafe for Validated<T>where
T: UnwindSafe,
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more