Skip to main content

larust_validation/
rules.rs

1//! Rule-checking functions operate on the raw (possibly-absent) string
2//! value for a field and return `Some(message)` on failure. Each rule is
3//! independent, matching Laravel's rule composition: an absent value
4//! doesn't trigger `email`/`length` - only `required` cares about absence.
5//!
6//! Every message goes through [`larust_lang::t_or`]/[`larust_lang::t_or_with`]
7//! rather than a bare literal - a `validation.*`-keyed entry in an app's own
8//! `resources/lang/{locale}.json` overrides the message below; an app with
9//! no such entry (nearly every app, today) still gets the exact English text
10//! that's always been hardcoded here, since `t_or`'s whole point (unlike
11//! `larust_lang::t`) is falling back to a real default instead of an
12//! unresolved, literal key reaching a user.
13
14pub fn required(value: Option<&str>) -> Option<String> {
15    match value {
16        Some(v) if !v.trim().is_empty() => None,
17        _ => Some(larust_lang::t_or(
18            "validation.required",
19            "This field is required.",
20        )),
21    }
22}
23
24pub fn email(value: Option<&str>) -> Option<String> {
25    match value {
26        Some(v) if !v.is_empty() && !is_valid_email(v) => Some(larust_lang::t_or(
27            "validation.email",
28            "This field must be a valid email address.",
29        )),
30        _ => None,
31    }
32}
33
34pub fn max_length(value: Option<&str>, max: usize) -> Option<String> {
35    match value {
36        Some(v) if v.chars().count() > max => Some(larust_lang::t_or_with(
37            "validation.max_length",
38            "This field must not be greater than :max characters.",
39            &[("max", &max.to_string())],
40        )),
41        _ => None,
42    }
43}
44
45pub fn min_length(value: Option<&str>, min: usize) -> Option<String> {
46    match value {
47        Some(v) if v.chars().count() < min => Some(larust_lang::t_or_with(
48            "validation.min_length",
49            "This field must be at least :min characters.",
50            &[("min", &min.to_string())],
51        )),
52        _ => None,
53    }
54}
55
56/// Laravel's `confirmed` rule: checks a field against a same-named
57/// `..._confirmation` field (e.g. `password` / `password_confirmation`).
58/// Unlike the other rules here, an *absent* confirmation value is itself a
59/// failure whenever the primary value is present and non-empty - a present
60/// `password` with no `password_confirmation` field submitted at all is a
61/// mismatch, not something to silently skip.
62pub fn confirmed(value: Option<&str>, confirmation: Option<&str>) -> Option<String> {
63    match value {
64        Some(v) if !v.is_empty() && Some(v) != confirmation => Some(larust_lang::t_or(
65            "validation.confirmed",
66            "This field confirmation does not match.",
67        )),
68        _ => None,
69    }
70}
71
72/// Minimal structural check (not full RFC 5322) - good enough for form
73/// validation UX. A dedicated crate can replace this later without
74/// changing the `rules::email` call sites.
75fn is_valid_email(value: &str) -> bool {
76    let Some((local, domain)) = value.split_once('@') else {
77        return false;
78    };
79    !local.is_empty() && domain.contains('.') && !domain.starts_with('.') && !domain.ends_with('.')
80}
81
82#[cfg(test)]
83mod tests {
84    use super::*;
85
86    #[test]
87    fn required_rejects_absent_and_blank() {
88        assert!(required(None).is_some());
89        assert!(required(Some("")).is_some());
90        assert!(required(Some("   ")).is_some());
91        assert!(required(Some("x")).is_none());
92    }
93
94    #[test]
95    fn email_only_fires_on_present_invalid_value() {
96        assert!(email(None).is_none());
97        assert!(email(Some("")).is_none());
98        assert!(email(Some("not-an-email")).is_some());
99        assert!(email(Some("a@b.com")).is_none());
100        assert!(email(Some("@b.com")).is_some());
101        assert!(email(Some("a@")).is_some());
102    }
103
104    #[test]
105    fn max_length_counts_chars_not_bytes() {
106        assert!(max_length(Some("hello"), 5).is_none());
107        assert!(max_length(Some("hello!"), 5).is_some());
108        assert!(max_length(None, 5).is_none());
109    }
110
111    #[test]
112    fn min_length_counts_chars_not_bytes() {
113        assert!(min_length(Some("hi"), 2).is_none());
114        assert!(min_length(Some("h"), 2).is_some());
115        assert!(min_length(None, 2).is_none());
116    }
117
118    #[test]
119    fn confirmed_accepts_matching_values() {
120        assert!(confirmed(Some("secret"), Some("secret")).is_none());
121    }
122
123    #[test]
124    fn confirmed_rejects_mismatched_values() {
125        assert!(confirmed(Some("secret"), Some("different")).is_some());
126    }
127
128    #[test]
129    fn confirmed_rejects_missing_confirmation_when_value_present() {
130        assert!(confirmed(Some("secret"), None).is_some());
131    }
132
133    #[test]
134    fn confirmed_does_not_fire_on_absent_or_empty_value() {
135        // Absence is `required`'s job, not `confirmed`'s - matches the
136        // rest of this module's convention (see the module doc comment).
137        assert!(confirmed(None, None).is_none());
138        assert!(confirmed(Some(""), None).is_none());
139    }
140}