form_validation/validatable.rs
1use crate::ValidationErrors;
2
3#[cfg(feature = "async")]
4use futures::Future;
5
6#[cfg(feature = "async")]
7use std::pin::Pin;
8
9/// An item that can be validated.
10pub trait Validatable<Key> {
11 /// Validate this item. Returns `Ok(())` if no errors were
12 /// encountered, and returns `Err(ValidationErrors)` if any errors
13 /// were encountered.
14 fn validate(&self) -> Result<(), ValidationErrors<Key>>;
15 /// Validate this item. Returns an empty
16 /// [ValidationErrors](ValidationErrors) if no errors were
17 /// encountered during validation.
18 fn validate_or_empty(&self) -> ValidationErrors<Key> {
19 match self.validate() {
20 Ok(()) => ValidationErrors::default(),
21 Err(errors) => errors,
22 }
23 }
24}
25
26/// An item that can be validated asynchronously.
27///
28/// See [Validatable] for the synchronous version.
29#[cfg(feature = "async")]
30#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
31pub trait AsyncValidatable<Key>
32where
33 Key: 'static,
34{
35 /// Creates a future that will validate this item. The future
36 /// returns `Ok(())` if no errors were encountered, and returns
37 /// `Err(ValidationErrors)` if any errors were encountered.
38 fn validate_future(&self) -> Pin<Box<dyn Future<Output = Result<(), ValidationErrors<Key>>>>>;
39 /// Creates a future that will validate this item. The future
40 /// returns an empty [ValidationErrors](ValidationErrors) if no
41 /// errors were encountered during validation.
42 fn validate_future_or_empty(&self) -> Pin<Box<dyn Future<Output = ValidationErrors<Key>>>> {
43 let future = self.validate_future();
44 Box::pin(async move {
45 let result: Result<(), ValidationErrors<Key>> = future.await;
46 match result {
47 Ok(()) => ValidationErrors::default(),
48 Err(errors) => errors,
49 }
50 })
51 }
52}