Skip to main content

aurelin_framework/
validation.rs

1//! Structured, user-facing validation failures.
2//!
3//! Codes are validator rule codes; custom rules should use stable, application-owned
4//! codes. Input values and arbitrary validator parameters are never copied into issues.
5//! This is a data contract, not a translation or message catalogue API.
6
7use std::collections::BTreeMap;
8
9use serde::{Deserialize, Serialize};
10use serde_json::Value;
11use validator::{ValidationErrors, ValidationErrorsKind};
12
13pub mod browser;
14pub mod http;
15
16/// A single failed rule at a concrete, dot-separated field path.
17#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
18pub struct ValidationIssue {
19    pub field: String,
20    pub code: String,
21    pub descriptor: MessageDescriptor,
22    pub arguments: BTreeMap<String, Value>,
23    #[serde(skip_serializing_if = "Option::is_none")]
24    pub bag: Option<String>,
25}
26
27/// A safe, unrendered default message. Validator-provided messages are not trusted.
28#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
29#[serde(rename_all = "snake_case")]
30pub enum MessageDescriptor {
31    Email,
32    Url,
33    Length,
34    Range,
35    Required,
36    Invalid,
37    /// Application-provided text explicitly approved for public display.
38    Custom(String),
39}
40
41impl ValidationIssue {
42    /// Replace the default with application-owned text safe for public display.
43    pub fn with_safe_message(mut self, message: impl Into<String>) -> Self {
44        self.descriptor = MessageDescriptor::Custom(message.into());
45        self
46    }
47
48    /// Render the descriptor at the presentation boundary.
49    pub fn render_message(&self) -> String {
50        match &self.descriptor {
51            MessageDescriptor::Custom(message) => message.clone(),
52            descriptor => {
53                let description = match descriptor {
54                    MessageDescriptor::Email => "must be a valid email address",
55                    MessageDescriptor::Url => "must be a valid URL",
56                    MessageDescriptor::Length => "has an invalid length",
57                    MessageDescriptor::Range => "is out of range",
58                    MessageDescriptor::Required => "is required",
59                    MessageDescriptor::Invalid => "is invalid",
60                    MessageDescriptor::Custom(_) => unreachable!(),
61                };
62                format!("The {} field {}.", self.field, description)
63            }
64        }
65    }
66}
67
68/// Convert validator errors without exposing rejected values or custom parameters.
69///
70/// Validator messages are ignored because custom validators can embed input.
71/// Custom rule codes are part of the application's public contract.
72pub fn issues(errors: &ValidationErrors, bag: Option<&str>) -> Vec<ValidationIssue> {
73    let mut result = Vec::new();
74    collect(errors, "", bag, &mut result);
75    result.sort_by(|a, b| a.field.cmp(&b.field).then(a.code.cmp(&b.code)));
76    result
77}
78
79fn collect(errors: &ValidationErrors, prefix: &str, bag: Option<&str>, result: &mut Vec<ValidationIssue>) {
80    for (field, kind) in errors.errors() {
81        let path = if prefix.is_empty() { field.to_string() } else { format!("{prefix}.{field}") };
82        match kind {
83            ValidationErrorsKind::Struct(nested) => collect(nested, &path, bag, result),
84            ValidationErrorsKind::List(items) => {
85                for (index, nested) in items {
86                    collect(nested, &format!("{path}.{index}"), bag, result);
87                }
88            }
89            ValidationErrorsKind::Field(errors) => {
90                for error in errors {
91                    let mut arguments = BTreeMap::new();
92                    if matches!(error.code.as_ref(), "length" | "range") {
93                        for key in ["min", "max", "equal"] {
94                            if let Some(value @ Value::Number(_)) = error.params.get(key) {
95                                arguments.insert(key.to_owned(), value.clone());
96                            }
97                        }
98                    }
99                    result.push(ValidationIssue {
100                        field: path.clone(),
101                        code: error.code.to_string(),
102                        descriptor: descriptor(&error.code),
103                        arguments,
104                        bag: bag.map(str::to_owned),
105                    });
106                }
107            }
108        }
109    }
110}
111
112fn descriptor(code: &str) -> MessageDescriptor {
113    match code {
114        "email" => MessageDescriptor::Email,
115        "url" => MessageDescriptor::Url,
116        "length" => MessageDescriptor::Length,
117        "range" => MessageDescriptor::Range,
118        "required" => MessageDescriptor::Required,
119        _ => MessageDescriptor::Invalid,
120    }
121}