Skip to main content

larust_validation/
errors.rs

1use axum::http::StatusCode;
2use axum::response::{IntoResponse, Response};
3use axum::Json;
4use std::collections::BTreeMap;
5
6/// Laravel-shaped validation error bag: field name -> messages.
7///
8/// `IntoResponse` renders it as a 422 with the same JSON shape Laravel's
9/// default validation exception produces:
10/// `{"message": "...", "errors": {"field": ["msg", ...]}}`.
11#[derive(Debug, Default)]
12pub struct ValidationErrors {
13    errors: BTreeMap<String, Vec<String>>,
14}
15
16impl ValidationErrors {
17    pub fn new() -> Self {
18        Self::default()
19    }
20
21    pub fn add(&mut self, field: &str, message: impl Into<String>) {
22        self.errors
23            .entry(field.to_string())
24            .or_default()
25            .push(message.into());
26    }
27
28    pub fn is_empty(&self) -> bool {
29        self.errors.is_empty()
30    }
31}
32
33#[derive(serde::Serialize)]
34struct ErrorBody<'a> {
35    message: String,
36    errors: &'a BTreeMap<String, Vec<String>>,
37}
38
39impl IntoResponse for ValidationErrors {
40    fn into_response(self) -> Response {
41        let body = ErrorBody {
42            message: larust_lang::t_or("validation.invalid_data", "The given data was invalid."),
43            errors: &self.errors,
44        };
45        (StatusCode::UNPROCESSABLE_ENTITY, Json(body)).into_response()
46    }
47}
48
49#[cfg(test)]
50mod tests {
51    use super::*;
52
53    #[test]
54    fn starts_empty() {
55        assert!(ValidationErrors::new().is_empty());
56    }
57
58    #[test]
59    fn add_accumulates_multiple_messages_per_field() {
60        let mut errors = ValidationErrors::new();
61        errors.add("email", "is required");
62        errors.add("email", "must be a valid email address");
63
64        assert!(!errors.is_empty());
65        assert_eq!(errors.errors.get("email").unwrap().len(), 2);
66    }
67}