Skip to main content

phoenix_validation/
lib.rs

1use std::{
2    borrow::Cow,
3    collections::BTreeMap,
4    ops::{Deref, DerefMut},
5};
6
7use phoenix_http::{FromRequest, IntoResponse, Json, Request, Response, StatusCode};
8use serde::Serialize;
9use serde_json::Value;
10use thiserror::Error;
11
12#[derive(Clone, Copy)]
13pub struct RuleContext<'a> {
14    pub field: &'a str,
15    pub value: Option<&'a Value>,
16    pub data: &'a Value,
17}
18
19pub trait Rule: Send + Sync + 'static {
20    fn name(&self) -> Cow<'static, str>;
21
22    /// Validate a field in the context of its full input payload.
23    ///
24    /// # Errors
25    ///
26    /// Returns a user-facing validation message when the field is invalid.
27    fn validate(&self, context: RuleContext<'_>) -> Result<(), String>;
28}
29
30pub type BoxedRule = Box<dyn Rule>;
31
32#[macro_export]
33macro_rules! rules {
34    ($($rule:expr),* $(,)?) => {{
35        let rules: ::std::vec::Vec<$crate::BoxedRule> =
36            ::std::vec![$(::std::boxed::Box::new($rule)),*];
37        rules
38    }};
39}
40
41pub struct CustomRule<F> {
42    name: Cow<'static, str>,
43    validate: F,
44}
45
46#[must_use]
47pub fn custom_rule<F>(name: impl Into<Cow<'static, str>>, validate: F) -> CustomRule<F>
48where
49    F: for<'a> Fn(RuleContext<'a>) -> Result<(), String> + Send + Sync + 'static,
50{
51    CustomRule {
52        name: name.into(),
53        validate,
54    }
55}
56
57impl<F> Rule for CustomRule<F>
58where
59    F: for<'a> Fn(RuleContext<'a>) -> Result<(), String> + Send + Sync + 'static,
60{
61    fn name(&self) -> Cow<'static, str> {
62        self.name.clone()
63    }
64
65    fn validate(&self, context: RuleContext<'_>) -> Result<(), String> {
66        (self.validate)(context)
67    }
68}
69
70pub struct Validator<'a> {
71    data: &'a Value,
72    rules: BTreeMap<String, Vec<Box<dyn Rule>>>,
73}
74
75impl<'a> Validator<'a> {
76    #[must_use]
77    pub fn new(data: &'a Value) -> Self {
78        Self {
79            data,
80            rules: BTreeMap::new(),
81        }
82    }
83
84    #[must_use]
85    pub fn field<I>(mut self, field: impl Into<String>, rules: I) -> Self
86    where
87        I: IntoIterator<Item = BoxedRule>,
88    {
89        self.rules.entry(field.into()).or_default().extend(rules);
90        self
91    }
92
93    /// Run every registered rule and collect field-level errors.
94    ///
95    /// # Errors
96    ///
97    /// Returns all [`ValidationErrors`] when one or more rules fail.
98    pub fn validate(&self) -> Result<(), ValidationErrors> {
99        let mut errors = BTreeMap::new();
100
101        for (field, rules) in &self.rules {
102            let value = value_at_path(self.data, field);
103            for rule in rules {
104                if let Err(message) = rule.validate(RuleContext {
105                    field,
106                    value,
107                    data: self.data,
108                }) {
109                    errors
110                        .entry(field.clone())
111                        .or_insert_with(Vec::new)
112                        .push(ValidationError {
113                            rule: rule.name().into_owned(),
114                            message,
115                        });
116                }
117            }
118        }
119
120        if errors.is_empty() {
121            Ok(())
122        } else {
123            Err(ValidationErrors { fields: errors })
124        }
125    }
126}
127
128#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
129pub struct ValidationError {
130    pub rule: String,
131    pub message: String,
132}
133
134#[derive(Clone, Debug, Error, Serialize, PartialEq, Eq)]
135#[error("validation failed")]
136pub struct ValidationErrors {
137    fields: BTreeMap<String, Vec<ValidationError>>,
138}
139
140pub trait Validate: Send + Sync + 'static {
141    /// Validate a deserialized request DTO.
142    ///
143    /// # Errors
144    ///
145    /// Returns stable field-level errors when the DTO is not valid.
146    fn validate(&self) -> Result<(), ValidationErrors>;
147}
148
149#[derive(Clone, Debug, PartialEq, Eq)]
150pub struct Validated<T>(pub T);
151
152impl<T> Deref for Validated<T> {
153    type Target = T;
154
155    fn deref(&self) -> &Self::Target {
156        &self.0
157    }
158}
159
160impl<T> DerefMut for Validated<T> {
161    fn deref_mut(&mut self) -> &mut Self::Target {
162        &mut self.0
163    }
164}
165
166#[derive(Debug)]
167pub enum ValidatedRejection<R> {
168    Extract(R),
169    Validation(ValidationErrors),
170}
171
172impl<R> IntoResponse for ValidatedRejection<R>
173where
174    R: IntoResponse,
175{
176    fn into_response(self) -> Response {
177        match self {
178            Self::Extract(rejection) => rejection.into_response(),
179            Self::Validation(errors) => {
180                #[derive(Serialize)]
181                struct ValidationBody<'a> {
182                    message: &'static str,
183                    errors: &'a BTreeMap<String, Vec<ValidationError>>,
184                }
185
186                Json(ValidationBody {
187                    message: "The submitted data is invalid.",
188                    errors: errors.fields(),
189                })
190                .into_response()
191                .with_status(StatusCode::UNPROCESSABLE_ENTITY)
192            }
193        }
194    }
195}
196
197impl<E, T> FromRequest for Validated<E>
198where
199    E: FromRequest + Deref<Target = T>,
200    T: Validate,
201{
202    type Rejection = ValidatedRejection<E::Rejection>;
203
204    fn from_request(request: &Request) -> Result<Self, Self::Rejection> {
205        let extracted = E::from_request(request).map_err(ValidatedRejection::Extract)?;
206        extracted
207            .deref()
208            .validate()
209            .map_err(ValidatedRejection::Validation)?;
210        Ok(Self(extracted))
211    }
212}
213
214impl ValidationErrors {
215    #[must_use]
216    pub fn get(&self, field: &str) -> Option<&[ValidationError]> {
217        self.fields.get(field).map(Vec::as_slice)
218    }
219
220    #[must_use]
221    pub fn fields(&self) -> &BTreeMap<String, Vec<ValidationError>> {
222        &self.fields
223    }
224}
225
226#[derive(Clone, Copy, Debug)]
227pub struct Required;
228
229#[must_use]
230pub const fn required() -> Required {
231    Required
232}
233
234impl Rule for Required {
235    fn name(&self) -> Cow<'static, str> {
236        Cow::Borrowed("required")
237    }
238
239    fn validate(&self, context: RuleContext<'_>) -> Result<(), String> {
240        let valid = match context.value {
241            None | Some(Value::Null) => false,
242            Some(Value::String(value)) => !value.trim().is_empty(),
243            Some(Value::Array(value)) => !value.is_empty(),
244            Some(Value::Object(value)) => !value.is_empty(),
245            Some(_) => true,
246        };
247        valid
248            .then_some(())
249            .ok_or_else(|| format!("The {} field is required.", context.field))
250    }
251}
252
253#[derive(Clone, Copy, Debug)]
254pub struct StringRule;
255
256#[must_use]
257pub const fn string() -> StringRule {
258    StringRule
259}
260
261impl Rule for StringRule {
262    fn name(&self) -> Cow<'static, str> {
263        Cow::Borrowed("string")
264    }
265
266    fn validate(&self, context: RuleContext<'_>) -> Result<(), String> {
267        match context.value {
268            None | Some(Value::Null | Value::String(_)) => Ok(()),
269            Some(_) => Err(format!("The {} field must be a string.", context.field)),
270        }
271    }
272}
273
274#[derive(Clone, Copy, Debug)]
275pub struct MinLength(usize);
276
277#[must_use]
278pub const fn min_length(length: usize) -> MinLength {
279    MinLength(length)
280}
281
282#[derive(Clone, Copy, Debug)]
283pub struct MaxLength(usize);
284
285#[must_use]
286pub const fn max_length(length: usize) -> MaxLength {
287    MaxLength(length)
288}
289
290impl Rule for MaxLength {
291    fn name(&self) -> Cow<'static, str> {
292        Cow::Borrowed("max_length")
293    }
294
295    fn validate(&self, context: RuleContext<'_>) -> Result<(), String> {
296        if let Some(Value::String(value)) = context.value
297            && value.chars().count() > self.0
298        {
299            return Err(format!(
300                "The {} field must not exceed {} characters.",
301                context.field, self.0
302            ));
303        }
304        Ok(())
305    }
306}
307
308impl Rule for MinLength {
309    fn name(&self) -> Cow<'static, str> {
310        Cow::Borrowed("min_length")
311    }
312
313    fn validate(&self, context: RuleContext<'_>) -> Result<(), String> {
314        if let Some(Value::String(value)) = context.value
315            && value.chars().count() < self.0
316        {
317            return Err(format!(
318                "The {} field must be at least {} characters.",
319                context.field, self.0
320            ));
321        }
322        Ok(())
323    }
324}
325
326fn value_at_path<'a>(data: &'a Value, field: &str) -> Option<&'a Value> {
327    field
328        .split('.')
329        .try_fold(data, |current, segment| current.get(segment))
330}
331
332#[cfg(test)]
333mod tests {
334    use phoenix_http::{Bytes, Handler, HeaderMap, HeaderValue, Method, Request, header, typed};
335    use serde::Deserialize;
336
337    use super::*;
338
339    #[derive(Deserialize)]
340    struct CreateUserInput {
341        name: String,
342    }
343
344    impl Validate for CreateUserInput {
345        fn validate(&self) -> Result<(), ValidationErrors> {
346            let data = serde_json::json!({ "name": self.name });
347            Validator::new(&data)
348                .field("name", rules![required(), string(), min_length(3)])
349                .validate()
350        }
351    }
352
353    #[tokio::test]
354    async fn validated_extractor_returns_dto_or_field_errors() {
355        let handler = typed(
356            |Validated(Json(input)): Validated<Json<CreateUserInput>>| async move {
357                Json(serde_json::json!({ "name": input.name }))
358            },
359        );
360        let request = |body: &'static [u8]| {
361            let mut headers = HeaderMap::new();
362            headers.insert(
363                header::CONTENT_TYPE,
364                HeaderValue::from_static("application/json"),
365            );
366            Request::from_parts(
367                Method::POST,
368                "/users".parse().expect("valid URI"),
369                headers,
370                Bytes::from_static(body),
371            )
372        };
373
374        let response = handler.call(request(br#"{"name":"Ada"}"#)).await;
375        assert_eq!(response.status(), StatusCode::OK);
376
377        let response = handler.call(request(br#"{"name":"A"}"#)).await;
378        assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
379        let body: Value = serde_json::from_slice(response.body()).expect("validation JSON");
380        assert_eq!(body["errors"]["name"][0]["rule"], "min_length");
381    }
382}