Skip to main content

renox_core/validation/
mod.rs

1//! Form validation with Laravel-style rules, database-backed `unique` and
2//! `exists`, and English messages (an app translates them in its lang files).
3//!
4//! ```
5//! # use renox::prelude::*;
6//! use serde::{Deserialize, Serialize};
7//!
8//! #[derive(Deserialize, Serialize)]
9//! struct ProductForm {
10//!     name: String,
11//!     price: i64,
12//!     email: Option<String>,
13//! }
14//!
15//! impl Validate for ProductForm {
16//!     fn rules(&self, v: &mut Validator) {
17//!         v.field("name", &self.name).required().max(100).unique("products", "name");
18//!         v.field("price", &self.price).label("sale price").min(1_000);
19//!         v.field("email", &self.email).email();
20//!     }
21//! }
22//!
23//! async fn store(State(db): State<Db>, back: Back, Valid(form): Valid<ProductForm>) -> Result<Back> {
24//!     // `form` passed every rule; invalid input never gets here.
25//! #   let _ = (db, form);
26//!     Ok(back)
27//! }
28//! ```
29
30pub(crate) mod extract;
31mod key_values;
32mod messages;
33pub(crate) mod nested;
34mod value;
35
36use std::collections::BTreeMap;
37
38use axum::http::StatusCode;
39use axum::response::{IntoResponse, Response};
40use serde::{Deserialize, Serialize};
41use serde_json::{Map, Value, json};
42
43pub use extract::Valid;
44pub use key_values::KeyValues;
45pub(crate) use messages::{render, template_for};
46pub use value::{FieldValue, Inspected};
47
48use crate::Result;
49use crate::db::{Db, DbValue, ToDbValue, quote};
50use chrono::NaiveDateTime;
51
52/// Validation errors: messages keyed by field name.
53#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
54#[serde(transparent)]
55pub struct Errors(BTreeMap<String, Vec<String>>);
56
57impl Errors {
58    /// No errors.
59    pub fn new() -> Self {
60        Self::default()
61    }
62
63    /// Adds `message` to the messages of `field`.
64    pub fn add(&mut self, field: impl Into<String>, message: impl Into<String>) {
65        self.0.entry(field.into()).or_default().push(message.into());
66    }
67
68    /// Whether there are no errors.
69    pub fn is_empty(&self) -> bool {
70        self.0.is_empty()
71    }
72
73    /// Whether `field` has at least one error.
74    pub fn has(&self, field: &str) -> bool {
75        self.0.contains_key(field)
76    }
77
78    /// The first message for a field.
79    pub fn first(&self, field: &str) -> Option<&str> {
80        self.0
81            .get(field)
82            .and_then(|m| m.first())
83            .map(String::as_str)
84    }
85
86    /// Every field with its messages, fields in alphabetical order.
87    pub fn iter(&self) -> impl Iterator<Item = (&str, &[String])> {
88        self.0.iter().map(|(f, m)| (f.as_str(), m.as_slice()))
89    }
90}
91
92/// Declares the rules for a form. Used by the `Valid<T>` extractor, which
93/// calls, in order: [`prepare`](Validate::prepare),
94/// [`authorize`](Validate::authorize), [`rules`](Validate::rules) and, when
95/// they pass, [`after`](Validate::after). Only `rules` is required.
96///
97/// ```
98/// # use renox::prelude::*;
99/// use renox::validation::FormContext;
100///
101/// #[derive(serde::Deserialize)]
102/// struct Invite { email: String, team_id: i64 }
103///
104/// impl Validate for Invite {
105///     // Laravel's prepareForValidation: tidy the input first.
106///     fn prepare(&mut self) {
107///         self.email = self.email.trim().to_lowercase();
108///     }
109///
110///     // Laravel's authorize: `false` answers 403 before any rule runs.
111///     async fn authorize(&self, form: &FormContext<'_>) -> Result<bool> {
112///         Ok(form.user.is_some_and(|user| user.has_role("owner")))
113///     }
114///
115///     fn rules(&self, v: &mut Validator) {
116///         v.field("email", &self.email).required().email();
117///     }
118///
119///     // Laravel's `after`: checks that need the database or several fields,
120///     // once the rules pass. Errors added here are shown like any other.
121///     async fn after(&self, form: &FormContext<'_>, errors: &mut Errors) -> Result {
122///         let members: i64 = renox::db::sql("SELECT COUNT(*) FROM team_user WHERE team_id = ?")
123///             .bind(self.team_id)
124///             .scalar(&form.state.db)
125///             .await?;
126///         if members >= 10 {
127///             errors.add("email", "This team is full (10 members).");
128///         }
129///         Ok(())
130///     }
131/// }
132/// ```
133pub trait Validate {
134    /// The named error bag this form's errors are flashed in (Laravel's
135    /// error bags), for a page with two forms that share field names, e.g.
136    /// `Some("login")` next to a sign-up form. Templates read them with
137    /// `error('email', bag='login')`. `#[validate(bag = "login")]` on a
138    /// derived struct sets it.
139    const ERROR_BAG: Option<&'static str> = None;
140
141    /// Declares the fields' rules on `v`; they run after `prepare` and `authorize`.
142    fn rules(&self, v: &mut Validator);
143
144    /// Tidies the input before anything checks it (Laravel's
145    /// `prepareForValidation`): trim, lowercase an email, fill a slug. The
146    /// form refilled after an error still shows what was typed.
147    fn prepare(&mut self) {}
148
149    /// Whether this request may send the form (Laravel's `authorize`), e.g.
150    /// only the team's owner invites. `false` answers 403 before the rules
151    /// run. It sees the input, so it runs once the input is read.
152    fn authorize(
153        &self,
154        form: &FormContext<'_>,
155    ) -> impl std::future::Future<Output = Result<bool>> + Send {
156        let _ = form;
157        std::future::ready(Ok(true))
158    }
159
160    /// Checks that need the database, another service or several fields,
161    /// once the rules pass (Laravel's `after`, and async rules). Add
162    /// errors with `errors.add(field, message)`.
163    fn after(
164        &self,
165        form: &FormContext<'_>,
166        errors: &mut Errors,
167    ) -> impl std::future::Future<Output = Result> + Send {
168        let _ = (form, errors);
169        std::future::ready(Ok(()))
170    }
171}
172
173/// `prepare`, `authorize` and `after` for a struct with
174/// `#[derive(Validate)]`, which writes `rules` from its `#[validate(…)]`
175/// attributes: add `#[validate(hooks)]` on the struct and implement the
176/// ones you need.
177///
178/// ```
179/// # use renox::prelude::*;
180/// use renox::validation::{FormContext, ValidateHooks};
181///
182/// #[derive(serde::Deserialize, Validate)]
183/// #[validate(hooks)]
184/// struct Invite {
185///     #[validate(required, email)]
186///     email: String,
187/// }
188///
189/// impl ValidateHooks for Invite {
190///     fn prepare(&mut self) {
191///         self.email = self.email.trim().to_lowercase();
192///     }
193///
194///     async fn authorize(&self, form: &FormContext<'_>) -> Result<bool> {
195///         Ok(form.user.is_some())
196///     }
197/// }
198/// ```
199pub trait ValidateHooks {
200    /// Tidies the input before anything checks it; see [`Validate::prepare`].
201    fn prepare(&mut self) {}
202
203    /// Whether this request may send the form; `false` answers 403. See
204    /// [`Validate::authorize`].
205    fn authorize(
206        &self,
207        form: &FormContext<'_>,
208    ) -> impl std::future::Future<Output = Result<bool>> + Send {
209        let _ = form;
210        std::future::ready(Ok(true))
211    }
212
213    /// Checks run once the rules pass; see [`Validate::after`].
214    fn after(
215        &self,
216        form: &FormContext<'_>,
217        errors: &mut Errors,
218    ) -> impl std::future::Future<Output = Result> + Send {
219        let _ = (form, errors);
220        std::future::ready(Ok(()))
221    }
222}
223
224/// What [`Validate::authorize`] and [`Validate::after`] see of the request.
225#[non_exhaustive]
226pub struct FormContext<'a> {
227    /// The app's state, e.g. for its database.
228    pub state: &'a crate::AppState,
229    /// The logged-in user, if any.
230    pub user: Option<&'a crate::auth::User>,
231    /// The request's HTTP method.
232    pub method: &'a axum::http::Method,
233    /// The request's path, without the query string.
234    pub path: &'a str,
235    /// The request's locale (`APP_LOCALE` when none was negotiated).
236    pub locale: &'a str,
237}
238
239struct Pending {
240    field: String,
241    label: String,
242    table: String,
243    column: String,
244    value: DbValue,
245    ignore_id: Option<crate::db::DbValue>,
246    /// Extra conditions (`where_eq`, `where_null`, `where_not_null`).
247    scope: Vec<ScopeCondition>,
248    unique: bool,
249    message: Option<String>,
250}
251
252/// A check that needs the request's user or a service, run by `finish`.
253struct AsyncCheck {
254    field: String,
255    label: String,
256    kind: AsyncKind,
257    message: Option<String>,
258}
259
260enum AsyncKind {
261    /// The logged-in user's password (Laravel's `current_password`).
262    CurrentPassword(String),
263    /// Not in a known data breach (Have I Been Pwned's range API).
264    Uncompromised(String),
265}
266
267/// A condition added to a `unique`/`exists` check.
268enum ScopeCondition {
269    Eq(String, DbValue),
270    Null(String),
271    NotNull(String),
272}
273
274impl ScopeCondition {
275    fn column(&self) -> &str {
276        match self {
277            Self::Eq(column, _) | Self::Null(column) | Self::NotNull(column) => column,
278        }
279    }
280}
281
282/// SQLite reads an unknown double-quoted column as a string literal, which
283/// would make `unique("t", "typo")` always pass; refuse unknown columns.
284async fn ensure_sqlite_column(db: &Db, table: &str, column: &str) -> Result {
285    let found: i64 = crate::db::sql("SELECT COUNT(*) FROM pragma_table_info(?) WHERE name = ?")
286        .bind(table)
287        .bind(column)
288        .scalar(db)
289        .await?;
290    if found == 0 {
291        return Err(anyhow::anyhow!(
292            "unique/exists rule: table `{table}` has no column `{column}`"
293        )
294        .into());
295    }
296    Ok(())
297}
298
299/// Collects rule failures. Rules run in order and stop at a field's first
300/// failure; rules other than `required` and `accepted` skip empty values.
301pub struct Validator {
302    /// The request language's lang file, for overridden messages and labels.
303    texts: Option<crate::i18n::Texts>,
304    errors: Errors,
305    pending: Vec<Pending>,
306    checks: Vec<AsyncCheck>,
307}
308
309impl Default for Validator {
310    fn default() -> Self {
311        Self::new()
312    }
313}
314
315impl Validator {
316    /// A validator with Renox's English messages.
317    pub fn new() -> Self {
318        Self {
319            texts: None,
320            errors: Errors::new(),
321            pending: Vec::new(),
322            checks: Vec::new(),
323        }
324    }
325
326    /// Messages and field names in `lang`, from the app's lang file
327    /// (`renox.validation.*`, `renox.validation.attributes.*`), e.g. for
328    /// rules run in a handler or a command: `Validator::new().in_lang(&lang)`.
329    pub fn in_lang(self, lang: &crate::Lang) -> Self {
330        self.with_texts(lang.texts())
331    }
332
333    /// Uses the app's translations of messages (`renox.validation.*`) and
334    /// field names (`renox.validation.attributes.*`).
335    pub(crate) fn with_texts(mut self, texts: crate::i18n::Texts) -> Self {
336        self.texts = Some(texts);
337        self
338    }
339
340    fn template(&self, key: &str) -> std::borrow::Cow<'static, str> {
341        messages::template_for(self.texts.as_ref(), key)
342    }
343
344    /// A field's name for messages: the app's translation
345    /// (`renox.validation.attributes.{name}`) or the name with spaces.
346    fn translated_label(&self, name: &str) -> Option<String> {
347        self.texts.as_ref().and_then(|t| {
348            t.get(&format!("renox.validation.attributes.{name}"))
349                .cloned()
350        })
351    }
352
353    fn label_for(&self, name: &str) -> String {
354        nested::label(name, |key| self.translated_label(key))
355    }
356
357    /// Rules for each item of a list, e.g. every tag or every uploaded
358    /// photo; errors are keyed `name.0`, `name.1`, … and labelled
359    /// "`name` #1", "#2", …
360    ///
361    /// ```
362    /// # use renox::prelude::*;
363    /// # struct Form { tags: Vec<String>, photos: Vec<Upload> }
364    /// # impl Validate for Form {
365    /// fn rules(&self, v: &mut Validator) {
366    ///     v.field("tags", &self.tags).max(5);
367    ///     v.each("tags", &self.tags, |tag| tag.required().max(20));
368    ///     v.each("photos", &self.photos, |photo| photo.image().max(2048));
369    /// }
370    /// # }
371    /// ```
372    pub fn each<T: FieldValue>(
373        &mut self,
374        name: &str,
375        items: &[T],
376        rules: impl for<'a> Fn(Field<'a>) -> Field<'a>,
377    ) {
378        let base = self.label_for(name);
379        for (i, item) in items.iter().enumerate() {
380            let key = format!("{name}.{i}");
381            let label = format!("{base} #{}", i + 1);
382            rules(self.field(&key, item).label(&label));
383        }
384    }
385
386    /// Each item's own `Validate` rules, for a list of structs (e.g. the
387    /// lines of an order sent as JSON); errors are keyed `name.0.field`.
388    pub fn nested<T: Validate>(&mut self, name: &str, items: &[T]) {
389        for (i, item) in items.iter().enumerate() {
390            let mut inner = Validator {
391                texts: self.texts.clone(),
392                errors: Errors::new(),
393                pending: Vec::new(),
394                checks: Vec::new(),
395            };
396            item.rules(&mut inner);
397            for (field, messages) in inner.errors.iter() {
398                for message in messages {
399                    self.errors
400                        .add(format!("{name}.{i}.{field}"), message.clone());
401                }
402            }
403            for mut pending in inner.pending {
404                pending.field = format!("{name}.{i}.{}", pending.field);
405                self.pending.push(pending);
406            }
407            for mut check in inner.checks {
408                check.field = format!("{name}.{i}.{}", check.field);
409                self.checks.push(check);
410            }
411        }
412    }
413
414    /// No two items of a list are the same (Laravel's `distinct`), e.g. the
415    /// emails invited at once; each repeat gets the error, keyed `name.i`.
416    pub fn distinct<T: FieldValue>(&mut self, name: &str, items: &[T]) {
417        let base = self.label_for(name);
418        let template = self.template("distinct");
419        let mut seen: Vec<Inspected> = Vec::new();
420        for (i, item) in items.iter().enumerate() {
421            let value = match item.inspect() {
422                Inspected::Text(text) => Inspected::Text(text.trim().to_lowercase()),
423                other => other,
424            };
425            if value == Inspected::Missing {
426                continue;
427            }
428            if seen.contains(&value) {
429                let label = format!("{base} #{}", i + 1);
430                self.errors
431                    .add(format!("{name}.{i}"), render(&template, &label, &[]));
432            } else {
433                seen.push(value);
434            }
435        }
436    }
437
438    /// Starts the rules for one field. The label in messages defaults to the
439    /// name with `_` replaced by spaces.
440    pub fn field<'v>(&'v mut self, name: &str, value: &impl FieldValue) -> Field<'v> {
441        let translated = self.translated_label(name).is_some();
442        let mut field = Field {
443            translated,
444            // `items.0.name` reads "name" (or the app's `items.*.name`).
445            label: self.label_for(name),
446            name: name.to_owned(),
447            value: value.inspect(),
448            db_value: value.db_value(),
449            failed: false,
450            last_pending: None,
451            last_check: None,
452            v: self,
453        };
454        // `NaN`, `inf` and `1e999` parse as floats, but aren't numbers anyone entered.
455        if let Inspected::Number(n) = field.value
456            && !n.is_finite()
457        {
458            field.fail("numeric", &[]);
459        }
460        field
461    }
462
463    /// Adds an error that no rule covers.
464    pub fn error(&mut self, field: &str, message: impl Into<String>) {
465        self.errors.add(field, message);
466    }
467
468    /// Runs the database checks and returns every error (empty when valid).
469    /// `current_password` fails here, as there's no user to check against,
470    /// and the breach check of `Password::uncompromised` is skipped; use
471    /// [`finish_for`](Self::finish_for) for those (`Valid<T>` does).
472    pub async fn finish(self, db: &Db) -> Result<Errors> {
473        self.finish_with(db, None, None).await
474    }
475
476    /// Like [`finish`](Self::finish), with the logged-in user for
477    /// `current_password` and the app's HTTP client for
478    /// `Password::uncompromised`.
479    pub async fn finish_for(
480        self,
481        state: &crate::AppState,
482        user: Option<&crate::auth::User>,
483    ) -> Result<Errors> {
484        self.finish_with(&state.db, Some(state), user).await
485    }
486
487    async fn finish_with(
488        self,
489        db: &Db,
490        state: Option<&crate::AppState>,
491        user: Option<&crate::auth::User>,
492    ) -> Result<Errors> {
493        let mut errors = self.errors;
494        for check in self.pending {
495            if errors.has(&check.field) {
496                continue;
497            }
498            let dialect = db.dialect();
499            if dialect == crate::db::Dialect::Sqlite {
500                ensure_sqlite_column(db, &check.table, &check.column).await?;
501                for condition in &check.scope {
502                    ensure_sqlite_column(db, &check.table, condition.column()).await?;
503                }
504            }
505            // Form input is text; PostgreSQL won't compare text with a number
506            // column, so compare as text (a no-op for text columns).
507            let column = match (&check.value, dialect) {
508                (DbValue::Text(_), crate::db::Dialect::Postgres) => {
509                    format!("CAST({} AS TEXT)", quote(&check.column))
510                }
511                _ => quote(&check.column),
512            };
513            let mut sql = format!(
514                "SELECT EXISTS(SELECT 1 FROM {} WHERE {column} = ?",
515                quote(&check.table),
516            );
517            if check.ignore_id.is_some() {
518                sql.push_str(" AND \"id\" != ?");
519            }
520            let mut scope_values = Vec::new();
521            for condition in check.scope {
522                match condition {
523                    ScopeCondition::Eq(column, value) => {
524                        sql.push_str(&format!(" AND {} = ?", quote(&column)));
525                        scope_values.push(value);
526                    }
527                    ScopeCondition::Null(column) => {
528                        sql.push_str(&format!(" AND {} IS NULL", quote(&column)));
529                    }
530                    ScopeCondition::NotNull(column) => {
531                        sql.push_str(&format!(" AND {} IS NOT NULL", quote(&column)));
532                    }
533                }
534            }
535            sql.push(')');
536            let mut query = crate::db::sql(sql).bind(check.value);
537            if let Some(id) = check.ignore_id {
538                query = query.bind(id);
539            }
540            let query = query.bind_all(scope_values);
541            let found: bool = query.scalar(db).await?;
542            if found == check.unique {
543                let key = if check.unique { "unique" } else { "exists" };
544                let message = check.message.unwrap_or_else(|| {
545                    render(
546                        &messages::template_for(self.texts.as_ref(), key),
547                        &check.label,
548                        &[],
549                    )
550                });
551                errors.add(check.field, message);
552            }
553        }
554        for check in self.checks {
555            if errors.has(&check.field) {
556                continue;
557            }
558            let key = match &check.kind {
559                AsyncKind::CurrentPassword(password) => match user {
560                    Some(user) if user.check_password(password).await => continue,
561                    _ => "current_password",
562                },
563                AsyncKind::Uncompromised(password) => match state {
564                    Some(state) if breached(state, password).await => "password.uncompromised",
565                    _ => continue,
566                },
567            };
568            let message = check.message.unwrap_or_else(|| {
569                render(
570                    &messages::template_for(self.texts.as_ref(), key),
571                    &check.label,
572                    &[],
573                )
574            });
575            errors.add(check.field, message);
576        }
577        Ok(errors)
578    }
579
580    /// Like `rules_of`, with the app's translations of messages and labels.
581    pub(crate) fn rules_with_texts(data: &impl Validate, texts: crate::i18n::Texts) -> Self {
582        let mut validator = Self::new().with_texts(texts);
583        data.rules(&mut validator);
584        validator
585    }
586
587    /// Applies `data`'s rules; call `finish` to run the database checks.
588    ///
589    /// ```
590    /// # use renox::prelude::*;
591    /// # #[derive(serde::Deserialize)] struct ProductForm { name: String }
592    /// # impl Validate for ProductForm { fn rules(&self, v: &mut Validator) { v.field("name", &self.name).required(); } }
593    /// # async fn demo(form: ProductForm, db: Db) -> Result {
594    /// let errors = Validator::rules_of(&form).finish(&db).await?;
595    /// # let _ = errors; Ok(()) }
596    /// ```
597    pub fn rules_of(data: &impl Validate) -> Self {
598        let mut validator = Self::new();
599        data.rules(&mut validator);
600        validator
601    }
602}
603
604/// The rules for one field, chained: `v.field("name", &self.name).required().max(100)`.
605pub struct Field<'v> {
606    v: &'v mut Validator,
607    name: String,
608    label: String,
609    /// The label came from the app's lang file.
610    translated: bool,
611    value: Inspected,
612    db_value: DbValue,
613    failed: bool,
614    last_pending: Option<usize>,
615    /// The `current_password`/`uncompromised` check just added, for `message`.
616    last_check: Option<usize>,
617}
618
619fn number(n: f64) -> String {
620    if n.fract() == 0.0 && n.abs() < 1e15 {
621        format!("{}", n as i64)
622    } else {
623        n.to_string()
624    }
625}
626
627impl Field<'_> {
628    /// The name used in messages, e.g. `.label("sale price")`.
629    pub fn label(mut self, label: &str) -> Self {
630        self.label = label.to_owned();
631        self
632    }
633
634    /// Uses `label` unless the app's lang file names this field.
635    pub(crate) fn fallback_label(mut self, label: &str) -> Self {
636        if !self.translated {
637            self.label = label.to_owned();
638        }
639        self
640    }
641
642    fn fail(&mut self, key: &str, params: &[(&str, String)]) {
643        if !self.failed {
644            let message = render(&self.v.template(key), &self.label, params);
645            self.v.errors.add(&self.name, message);
646            self.failed = true;
647            self.last_pending = None;
648            self.last_check = None;
649        }
650    }
651
652    fn check(&mut self, kind: AsyncKind) {
653        self.v.checks.push(AsyncCheck {
654            field: self.name.clone(),
655            label: self.label.clone(),
656            kind,
657            message: None,
658        });
659        self.last_pending = None;
660        self.last_check = Some(self.v.checks.len() - 1);
661    }
662
663    fn present(&self) -> bool {
664        !self.failed && self.value != Inspected::Missing
665    }
666
667    /// Replaces this field's error so far with `message`: the error of the
668    /// rule just before it, or of any earlier rule that failed (only one error
669    /// is kept per field). A database or async check just before it gets the
670    /// message when it fails.
671    pub fn message(self, message: impl Into<String>) -> Self {
672        let message = message.into();
673        if let Some(i) = self.last_pending {
674            self.v.pending[i].message = Some(message);
675        } else if let Some(i) = self.last_check {
676            self.v.checks[i].message = Some(message);
677        } else if self.failed
678            && let Some(last) = self
679                .v
680                .errors
681                .0
682                .get_mut(&self.name)
683                .and_then(|messages| messages.last_mut())
684        {
685            *last = message;
686        }
687        self
688    }
689
690    /// Fails when the value is missing: `None`, or text that is blank after trimming.
691    pub fn required(mut self) -> Self {
692        if !self.failed && self.value == Inspected::Missing {
693            self.fail("required", &[]);
694        }
695        self
696    }
697
698    fn size_rule(
699        mut self,
700        kind: &str,
701        ok: impl Fn(f64) -> bool,
702        params: &[(&str, String)],
703    ) -> Self {
704        if !self.present() {
705            return self;
706        }
707        let (size, suffix) = match &self.value {
708            Inspected::Text(text) => (text.chars().count() as f64, "string"),
709            Inspected::Number(n) => (*n, "numeric"),
710            Inspected::Items(n) => (*n as f64, "array"),
711            Inspected::File { kilobytes, .. } => (*kilobytes, "file"),
712            _ => return self,
713        };
714        if !ok(size) {
715            self.fail(&format!("{kind}.{suffix}"), params);
716        }
717        self
718    }
719
720    /// At least `min` characters, items, kilobytes (files), or as a number.
721    pub fn min(self, min: impl Into<f64>) -> Self {
722        let min = min.into();
723        self.size_rule("min", |s| s >= min, &[("min", number(min))])
724    }
725
726    /// At most `max` characters, items, kilobytes (files), or as a number.
727    pub fn max(self, max: impl Into<f64>) -> Self {
728        let max = max.into();
729        self.size_rule("max", |s| s <= max, &[("max", number(max))])
730    }
731
732    /// Between `min` and `max` inclusive, measured as `min`/`max` do.
733    pub fn between(self, min: impl Into<f64>, max: impl Into<f64>) -> Self {
734        let (min, max) = (min.into(), max.into());
735        self.size_rule(
736            "between",
737            |s| s >= min && s <= max,
738            &[("min", number(min)), ("max", number(max))],
739        )
740    }
741
742    /// An email address: something before a single `@`, a dotted domain, no spaces.
743    pub fn email(mut self) -> Self {
744        if let (true, Inspected::Text(text)) = (self.present(), &self.value)
745            && !is_email(text)
746        {
747            self.fail("email", &[]);
748        }
749        self
750    }
751
752    /// An `http://` or `https://` URL with a host and no spaces.
753    pub fn url(mut self) -> Self {
754        if let (true, Inspected::Text(text)) = (self.present(), &self.value)
755            && !is_url(text)
756        {
757            self.fail("url", &[]);
758        }
759        self
760    }
761
762    /// An uploaded image: PNG, JPEG, GIF or WebP, checked from the file's
763    /// content rather than its name.
764    pub fn image(mut self) -> Self {
765        if let (true, Inspected::File { image, .. }) = (self.present(), &self.value)
766            && !*image
767        {
768            self.fail("image", &[]);
769        }
770        self
771    }
772
773    /// An uploaded file of one of these types, e.g. `&["jpg", "png", "pdf"]`
774    /// (`jpeg` counts as `jpg`). The content decides for the formats Renox can
775    /// recognise, the file name for the rest.
776    pub fn mimes(mut self, extensions: &[&str]) -> Self {
777        if let (true, Inspected::File { extension, .. }) = (self.present(), &self.value) {
778            let normalise = |e: &str| match e.to_ascii_lowercase().as_str() {
779                "jpeg" => "jpg".to_owned(),
780                other => other.to_owned(),
781            };
782            let ok = extensions
783                .iter()
784                .any(|e| normalise(e) == normalise(extension));
785            if !ok {
786                self.fail("mimes", &[("values", extensions.join(", "))]);
787            }
788        }
789        self
790    }
791
792    /// One of the given values (Laravel's `in`).
793    pub fn one_of<V: FieldValue>(mut self, allowed: &[V]) -> Self {
794        if self.present() && !allowed.iter().any(|a| a.inspect() == self.value) {
795            self.fail("in", &[]);
796        }
797        self
798    }
799
800    /// Equal to its confirmation field, e.g. `password` and `password_confirmation`.
801    pub fn confirmed(mut self, confirmation: &impl FieldValue) -> Self {
802        if self.present() && confirmation.inspect() != self.value {
803            self.fail("confirmed", &[]);
804        }
805        self
806    }
807
808    /// A checkbox that must be ticked.
809    pub fn accepted(mut self) -> Self {
810        if !self.failed && self.value != Inspected::Bool(true) {
811            self.fail("accepted", &[]);
812        }
813        self
814    }
815
816    /// A custom check: fails with `message` when `valid` is false.
817    pub fn rule(mut self, valid: bool, message: impl Into<String>) -> Self {
818        if !self.failed && !valid {
819            self.v.errors.add(&self.name, message);
820            self.failed = true;
821            self.last_pending = None;
822            self.last_check = None;
823        }
824        self
825    }
826
827    /// The whole text matches `pattern` (a regular expression; anchor it
828    /// with `^…$` to match all of it), e.g. `.matches(r"^[A-Z]{2}\d{4}$")`.
829    pub fn matches(mut self, pattern: &str) -> Self {
830        if let (true, Inspected::Text(text)) = (self.present(), &self.value) {
831            let ok = match cached_regex(pattern) {
832                Ok(regex) => regex.is_match(text),
833                Err(err) => {
834                    tracing::error!(pattern, error = %err, "invalid pattern in a `matches` rule");
835                    false
836                }
837            };
838            if !ok {
839                self.fail("regex", &[]);
840            }
841        }
842        self
843    }
844
845    /// Exactly `n` digits (and nothing else), e.g. a PIN.
846    pub fn digits(mut self, n: usize) -> Self {
847        if self.present() && digit_count(&self.value) != Some(n) {
848            self.fail("digits", &[("digits", n.to_string())]);
849        }
850        self
851    }
852
853    /// Between `min` and `max` digits (and nothing else), e.g. a phone number.
854    pub fn digits_between(mut self, min: usize, max: usize) -> Self {
855        if self.present() && !digit_count(&self.value).is_some_and(|n| n >= min && n <= max) {
856            self.fail(
857                "digits_between",
858                &[("min", min.to_string()), ("max", max.to_string())],
859            );
860        }
861        self
862    }
863
864    /// A date (`2026-10-01`) or a date and time (`2026-10-01T10:30`).
865    pub fn date(mut self) -> Self {
866        if self.present() && self.as_date().is_none() {
867            self.fail("date", &[]);
868        }
869        self
870    }
871
872    fn date_rule(
873        mut self,
874        key: &str,
875        limit: NaiveDateTime,
876        ok: impl Fn(NaiveDateTime, NaiveDateTime) -> bool,
877    ) -> Self {
878        if !self.present() {
879            return self;
880        }
881        match self.as_date() {
882            None => self.fail("date", &[]),
883            Some(date) if !ok(date, limit) => {
884                let shown = if limit.time() == chrono::NaiveTime::MIN {
885                    limit.date().to_string()
886                } else {
887                    limit.format("%Y-%m-%d %H:%M").to_string()
888                };
889                self.fail(key, &[("date", shown)]);
890            }
891            Some(_) => {}
892        }
893        self
894    }
895
896    /// A date before `limit` (a `NaiveDate`, `NaiveDateTime` or `DateTime`,
897    /// or text such as `"2026-01-01"`), e.g. `.before(today)` for a birth date.
898    pub fn before(self, limit: impl FieldValue) -> Self {
899        match limit_date(&limit) {
900            Some(limit) => self.date_rule("before", limit, |d, l| d < l),
901            None => self,
902        }
903    }
904
905    /// A date on or before `limit`.
906    pub fn before_or_equal(self, limit: impl FieldValue) -> Self {
907        match limit_date(&limit) {
908            Some(limit) => self.date_rule("before_or_equal", limit, |d, l| d <= l),
909            None => self,
910        }
911    }
912
913    /// A date after `limit`, e.g. `.after(self.start)` for an end date.
914    pub fn after(self, limit: impl FieldValue) -> Self {
915        match limit_date(&limit) {
916            Some(limit) => self.date_rule("after", limit, |d, l| d > l),
917            None => self,
918        }
919    }
920
921    /// A date on or after `limit`.
922    pub fn after_or_equal(self, limit: impl FieldValue) -> Self {
923        match limit_date(&limit) {
924            Some(limit) => self.date_rule("after_or_equal", limit, |d, l| d >= l),
925            None => self,
926        }
927    }
928
929    fn as_date(&self) -> Option<NaiveDateTime> {
930        match &self.value {
931            Inspected::Date(date) => Some(*date),
932            Inspected::Text(text) => parse_date(text.trim()),
933            _ => None,
934        }
935    }
936
937    /// None of the given values (Laravel's `not_in`).
938    pub fn none_of<V: FieldValue>(mut self, refused: &[V]) -> Self {
939        if self.present() && refused.iter().any(|r| r.inspect() == self.value) {
940            self.fail("not_in", &[]);
941        }
942        self
943    }
944
945    fn text_rule(
946        mut self,
947        key: &str,
948        ok: impl Fn(&str) -> bool,
949        params: &[(&str, String)],
950    ) -> Self {
951        if let (true, Inspected::Text(text)) = (self.present(), &self.value)
952            && !ok(text)
953        {
954            self.fail(key, params);
955        }
956        self
957    }
958
959    /// Letters only (any language's: `é`, `ü`, `ß` count).
960    pub fn alpha(self) -> Self {
961        self.text_rule("alpha", |t| t.chars().all(char::is_alphabetic), &[])
962    }
963
964    /// Letters and digits only.
965    pub fn alpha_num(self) -> Self {
966        self.text_rule("alpha_num", |t| t.chars().all(char::is_alphanumeric), &[])
967    }
968
969    /// Letters, digits, `-` and `_`, e.g. a username or a slug.
970    pub fn alpha_dash(self) -> Self {
971        self.text_rule(
972            "alpha_dash",
973            |t| {
974                t.chars()
975                    .all(|c| c.is_alphanumeric() || c == '-' || c == '_')
976            },
977            &[],
978        )
979    }
980
981    /// No uppercase letters.
982    pub fn lowercase(self) -> Self {
983        self.text_rule("lowercase", |t| !t.chars().any(char::is_uppercase), &[])
984    }
985
986    /// No lowercase letters.
987    pub fn uppercase(self) -> Self {
988        self.text_rule("uppercase", |t| !t.chars().any(char::is_lowercase), &[])
989    }
990
991    /// Starts with one of `prefixes`, e.g. `.starts_with(&["08", "+62"])`.
992    pub fn starts_with(self, prefixes: &[&str]) -> Self {
993        let values = prefixes.join(", ");
994        self.text_rule(
995            "starts_with",
996            |t| prefixes.iter().any(|p| t.starts_with(p)),
997            &[("values", values)],
998        )
999    }
1000
1001    /// Ends with one of `suffixes`, e.g. `.ends_with(&["@company.com"])`.
1002    pub fn ends_with(self, suffixes: &[&str]) -> Self {
1003        let values = suffixes.join(", ");
1004        self.text_rule(
1005            "ends_with",
1006            |t| suffixes.iter().any(|s| t.ends_with(s)),
1007            &[("values", values)],
1008        )
1009    }
1010
1011    /// A UUID (`8-4-4-4-12` hexadecimal digits).
1012    pub fn uuid(self) -> Self {
1013        self.text_rule("uuid", is_uuid, &[])
1014    }
1015
1016    /// An IPv4 or IPv6 address.
1017    pub fn ip(self) -> Self {
1018        self.text_rule("ip", |t| t.trim().parse::<std::net::IpAddr>().is_ok(), &[])
1019    }
1020
1021    /// Exactly `size` characters, items, kilobytes (files), or equal to it as
1022    /// a number (Laravel's `size`).
1023    pub fn size(self, size: impl Into<f64>) -> Self {
1024        let size = size.into();
1025        self.size_rule("size", |s| s == size, &[("size", number(size))])
1026    }
1027
1028    /// Required when `other` is empty, e.g. an email when there's no phone.
1029    pub fn required_without(self, other: &impl FieldValue) -> Self {
1030        let missing = other.inspect() == Inspected::Missing;
1031        self.required_if(missing)
1032    }
1033
1034    /// Must be empty when `condition` holds (Laravel's `prohibited_if`), e.g.
1035    /// no discount code on a gift card order.
1036    pub fn prohibited_if(mut self, condition: bool) -> Self {
1037        if condition && !self.failed && self.value != Inspected::Missing {
1038            self.fail("prohibited", &[]);
1039        }
1040        self
1041    }
1042
1043    /// Required when `condition` holds, e.g.
1044    /// `.required_if(self.kind == "company")` for a company name.
1045    pub fn required_if(self, condition: bool) -> Self {
1046        if condition { self.required() } else { self }
1047    }
1048
1049    /// Required unless `condition` holds.
1050    pub fn required_unless(self, condition: bool) -> Self {
1051        self.required_if(!condition)
1052    }
1053
1054    /// Required when `other` has a value, e.g. a phone number's country
1055    /// code when a phone number is given.
1056    pub fn required_with(self, other: &impl FieldValue) -> Self {
1057        let given = other.inspect() != Inspected::Missing;
1058        self.required_if(given)
1059    }
1060
1061    /// Equal to another field, named `other` in the message.
1062    pub fn same(mut self, other: &str, value: &impl FieldValue) -> Self {
1063        if self.present() && value.inspect() != self.value {
1064            let other = self.v.label_for(other);
1065            self.fail("same", &[("other", other)]);
1066        }
1067        self
1068    }
1069
1070    /// Different from another field, named `other` in the message.
1071    pub fn different(mut self, other: &str, value: &impl FieldValue) -> Self {
1072        if self.present() && value.inspect() == self.value {
1073            let other = self.v.label_for(other);
1074            self.fail("different", &[("other", other)]);
1075        }
1076        self
1077    }
1078
1079    fn compare_rule(
1080        mut self,
1081        key: &str,
1082        other: &str,
1083        value: &impl FieldValue,
1084        ok: fn(std::cmp::Ordering) -> bool,
1085    ) -> Self {
1086        if !self.present() {
1087            return self;
1088        }
1089        let other_value = value.inspect();
1090        if other_value == Inspected::Missing {
1091            return self;
1092        }
1093        // Two texts that both read as numbers compare as numbers (a price
1094        // in a `String`); other text compares by length.
1095        let both_numeric = matches!(
1096            (&self.value, &other_value),
1097            (Inspected::Text(_), Inspected::Text(_))
1098        ) && numeric_value(&self.value).is_some()
1099            && numeric_value(&other_value).is_some();
1100        let measured = |value: &Inspected| -> Option<(f64, &'static str)> {
1101            match value {
1102                Inspected::Text(_) if both_numeric => Some((numeric_value(value)?, "numeric")),
1103                Inspected::Number(n) => Some((*n, "numeric")),
1104                Inspected::Text(text) => Some((text.chars().count() as f64, "string")),
1105                Inspected::Items(n) => Some((*n as f64, "array")),
1106                Inspected::File { kilobytes, .. } => Some((*kilobytes, "file")),
1107                _ => None,
1108            }
1109        };
1110        let label = self.v.label_for(other);
1111        // Dates compare as dates, whatever form they came in.
1112        let as_date = |value: &Inspected| match value {
1113            Inspected::Date(date) => Some(*date),
1114            Inspected::Text(text) => parse_date(text.trim()),
1115            _ => None,
1116        };
1117        let dates = as_date(&self.value).zip(as_date(&other_value));
1118        if let Some((a, b)) = dates {
1119            if !ok(a.cmp(&b)) {
1120                self.fail(&format!("{key}.date"), &[("other", label)]);
1121            }
1122            return self;
1123        }
1124        match (measured(&self.value), measured(&other_value)) {
1125            (Some((a, kind)), Some((b, other_kind))) if kind == other_kind => {
1126                if !a.partial_cmp(&b).is_some_and(ok) {
1127                    self.fail(&format!("{key}.{kind}"), &[("other", label)]);
1128                }
1129            }
1130            _ => self.fail(&format!("{key}.numeric"), &[("other", label)]),
1131        }
1132        self
1133    }
1134
1135    /// Greater than another field (Laravel's `gt`), named `other` in the
1136    /// message: numbers by value (also two texts that both read as
1137    /// numbers), dates by date, other text by length, lists by items,
1138    /// files by size, e.g. a maximum price above the minimum. Skipped when
1139    /// the other field is empty.
1140    pub fn gt(self, other: &str, value: &impl FieldValue) -> Self {
1141        self.compare_rule("gt", other, value, |o| o.is_gt())
1142    }
1143
1144    /// Greater than or equal to another field; see [`gt`](Self::gt).
1145    pub fn gte(self, other: &str, value: &impl FieldValue) -> Self {
1146        self.compare_rule("gte", other, value, |o| o.is_ge())
1147    }
1148
1149    /// Less than another field; see [`gt`](Self::gt).
1150    pub fn lt(self, other: &str, value: &impl FieldValue) -> Self {
1151        self.compare_rule("lt", other, value, |o| o.is_lt())
1152    }
1153
1154    /// Less than or equal to another field; see [`gt`](Self::gt).
1155    pub fn lte(self, other: &str, value: &impl FieldValue) -> Self {
1156        self.compare_rule("lte", other, value, |o| o.is_le())
1157    }
1158
1159    /// A number with `min` to `max` decimal places (Laravel's `decimal`),
1160    /// e.g. `.decimal(2, 2)` for a price typed as `12.50`. A text field
1161    /// keeps what was typed; an `f64` field has lost trailing zeros
1162    /// (`12.50` is `12.5`), so check prices as text.
1163    pub fn decimal(mut self, min: usize, max: usize) -> Self {
1164        if !self.present() {
1165            return self;
1166        }
1167        let text = match &self.value {
1168            Inspected::Text(text) => text.trim().to_owned(),
1169            Inspected::Number(n) => n.to_string(),
1170            _ => String::new(),
1171        };
1172        let places = decimal_places(&text);
1173        if !places.is_some_and(|p| p >= min && p <= max) {
1174            let places = if min == max {
1175                min.to_string()
1176            } else {
1177                format!("{min}-{max}")
1178            };
1179            self.fail("decimal", &[("decimal", places)]);
1180        }
1181        self
1182    }
1183
1184    /// An ISO 4217 currency code such as `USD` or `aed` (see
1185    /// [`Currency`](crate::money::Currency)); the table is the one `Money` uses.
1186    pub fn currency(mut self) -> Self {
1187        if let (true, Inspected::Text(text)) = (self.present(), &self.value)
1188            && crate::money::Currency::parse(text.trim()).is_err()
1189        {
1190            self.fail("currency", &[]);
1191        }
1192        self
1193    }
1194
1195    /// An amount in whole units of `currency` (a code such as `"USD"`, often
1196    /// another field: `.money(&self.currency)`), typed as `12.50`: digits with
1197    /// at most the currency's decimals (JPY 0, USD 2, KWD 3), never rounded.
1198    /// An unknown `currency` leaves the rule out; check that field with
1199    /// [`currency`](Self::currency).
1200    pub fn money(mut self, currency: &str) -> Self {
1201        let Ok(currency) = crate::money::Currency::parse(currency.trim()) else {
1202            return self;
1203        };
1204        if let (true, Inspected::Text(text)) = (self.present(), &self.value)
1205            && crate::money::Money::parse(text, currency).is_err()
1206        {
1207            let decimals = currency.decimals().to_string();
1208            self.fail("money", &[("decimals", decimals)]);
1209        }
1210        self
1211    }
1212
1213    /// A decimal quantity typed as `12.5`, with at most `scale` decimals
1214    /// (`Quantity<3>` is `.quantity(3)`), never rounded: `12.500` passes,
1215    /// `12.5001` fails. For limits use [`quantity_min`](Self::quantity_min) and
1216    /// [`quantity_max`](Self::quantity_max): `min` and `max` count characters in text.
1217    pub fn quantity(mut self, scale: u32) -> Self {
1218        if let (true, Inspected::Text(text)) = (self.present(), &self.value)
1219            && !crate::quantity::fits_scale(text, scale)
1220        {
1221            self.fail("quantity", &[("decimals", scale.to_string())]);
1222        }
1223        self
1224    }
1225
1226    /// A quantity of at least `min` (a decimal such as `"0"` or `"0.5"`),
1227    /// compared as a number, not as text. Text that is not a decimal passes
1228    /// here; [`quantity`](Self::quantity) reports it.
1229    pub fn quantity_min(mut self, min: &str) -> Self {
1230        if let (true, Inspected::Text(text)) = (self.present(), &self.value)
1231            && let (Some(value), Some(limit)) =
1232                (crate::quantity::nano(text), crate::quantity::nano(min))
1233            && value < limit
1234        {
1235            self.fail("quantity_min", &[("min", min.trim().to_owned())]);
1236        }
1237        self
1238    }
1239
1240    /// A quantity of at most `max`, compared as a number; see
1241    /// [`quantity_min`](Self::quantity_min).
1242    pub fn quantity_max(mut self, max: &str) -> Self {
1243        if let (true, Inspected::Text(text)) = (self.present(), &self.value)
1244            && let (Some(value), Some(limit)) =
1245                (crate::quantity::nano(text), crate::quantity::nano(max))
1246            && value > limit
1247        {
1248            self.fail("quantity_max", &[("max", max.trim().to_owned())]);
1249        }
1250        self
1251    }
1252
1253    /// A latitude: a number, or text such as `25.2048`, from -90 to 90.
1254    pub fn latitude(mut self) -> Self {
1255        if self.present()
1256            && !numeric_value(&self.value).is_some_and(|n| (-90.0..=90.0).contains(&n))
1257        {
1258            self.fail("latitude", &[]);
1259        }
1260        self
1261    }
1262
1263    /// A longitude: a number, or text such as `55.2708`, from -180 to 180.
1264    pub fn longitude(mut self) -> Self {
1265        if self.present()
1266            && !numeric_value(&self.value).is_some_and(|n| (-180.0..=180.0).contains(&n))
1267        {
1268            self.fail("longitude", &[]);
1269        }
1270        self
1271    }
1272
1273    /// A point as JSON text: `{"lat": 25.2, "lng": 55.3}` or a GeoJSON
1274    /// `Point` (`[lng, lat]`). An out-of-range coordinate gets the
1275    /// `latitude` or `longitude` message, anything else the `point` one.
1276    pub fn point(mut self) -> Self {
1277        if let (true, Inspected::Text(text)) = (self.present(), &self.value)
1278            && let Err(e) = crate::geo::parse_point(text)
1279        {
1280            self.fail(e.rule_key(), &[]);
1281        }
1282        self
1283    }
1284
1285    /// A unit code that `units` knows, e.g. `.unit(&units)` with a
1286    /// [`UnitTable`](crate::quantity::UnitTable) from `Units::build`.
1287    pub fn unit(mut self, units: &crate::quantity::UnitTable) -> Self {
1288        if let (true, Inspected::Text(text)) = (self.present(), &self.value)
1289            && !units.contains(text.trim())
1290        {
1291            self.fail("unit", &[]);
1292        }
1293        self
1294    }
1295
1296    /// An uploaded image within `limits`, e.g.
1297    /// `.dimensions(&Dimensions::new().min_width(400).ratio(16, 9))`; see
1298    /// [`Dimensions`]. A file that isn't an image fails.
1299    pub fn dimensions(mut self, limits: &Dimensions) -> Self {
1300        if let (true, Inspected::File { dimensions, .. }) = (self.present(), &self.value) {
1301            let ok = dimensions.is_some_and(|(w, h)| limits.allows(w, h));
1302            if !ok {
1303                self.fail("dimensions", &[]);
1304            }
1305        }
1306        self
1307    }
1308
1309    /// Must be empty (Laravel's `prohibited`), e.g. a field only an admin
1310    /// may send, checked for everyone else.
1311    pub fn prohibited(self) -> Self {
1312        self.prohibited_if(true)
1313    }
1314
1315    /// Must be empty unless `condition` holds.
1316    pub fn prohibited_unless(self, condition: bool) -> Self {
1317        self.prohibited_if(!condition)
1318    }
1319
1320    /// When this field has a value, `other` must be empty (Laravel's
1321    /// `prohibits`), e.g. a coupon code and a gift card can't both be used.
1322    pub fn prohibits(mut self, other: &str, value: &impl FieldValue) -> Self {
1323        if self.present() && value.inspect() != Inspected::Missing {
1324            let other = self.v.label_for(other);
1325            self.fail("prohibits", &[("other", other)]);
1326        }
1327        self
1328    }
1329
1330    /// Required when every one of `others` has a value.
1331    pub fn required_with_all(self, others: &[&dyn FieldValue]) -> Self {
1332        let all = others.iter().all(|o| o.inspect() != Inspected::Missing);
1333        self.required_if(all)
1334    }
1335
1336    /// Required when none of `others` has a value, e.g. one way to reach
1337    /// the customer at least.
1338    pub fn required_without_all(self, others: &[&dyn FieldValue]) -> Self {
1339        let none = others.iter().all(|o| o.inspect() == Inspected::Missing);
1340        self.required_if(none)
1341    }
1342
1343    /// An integer of at least `min` digits.
1344    pub fn min_digits(mut self, min: usize) -> Self {
1345        if self.present() && !integer_digits(&self.value).is_some_and(|n| n >= min) {
1346            self.fail("min_digits", &[("min", min.to_string())]);
1347        }
1348        self
1349    }
1350
1351    /// An integer of at most `max` digits.
1352    pub fn max_digits(mut self, max: usize) -> Self {
1353        if self.present() && !integer_digits(&self.value).is_some_and(|n| n <= max) {
1354            self.fail("max_digits", &[("max", max.to_string())]);
1355        }
1356        self
1357    }
1358
1359    /// A multiple of `step`, e.g. `.multiple_of(500)` for amounts in
1360    /// steps of 500, or `.multiple_of(0.25)`.
1361    pub fn multiple_of(mut self, step: impl Into<f64>) -> Self {
1362        let step = step.into();
1363        if !self.present() {
1364            return self;
1365        }
1366        let ok = numeric_value(&self.value).is_some_and(|n| {
1367            let ratio = n / step;
1368            step != 0.0 && (ratio - ratio.round()).abs() < 1e-9
1369        });
1370        if !ok {
1371            self.fail("multiple_of", &[("value", number(step))]);
1372        }
1373        self
1374    }
1375
1376    /// A number: a number field, or text that reads as one (`12`, `-3.5`).
1377    pub fn numeric(mut self) -> Self {
1378        if self.present() && numeric_value(&self.value).is_none() {
1379            self.fail("numeric", &[]);
1380        }
1381        self
1382    }
1383
1384    /// A whole number: a number field without a fraction, or text that
1385    /// reads as one.
1386    pub fn integer(mut self) -> Self {
1387        if self.present() && !numeric_value(&self.value).is_some_and(|n| n.fract() == 0.0) {
1388            self.fail("integer", &[]);
1389        }
1390        self
1391    }
1392
1393    /// Valid JSON text, e.g. a settings field edited by hand.
1394    pub fn json(self) -> Self {
1395        self.text_rule(
1396            "json",
1397            |t| serde_json::from_str::<serde_json::Value>(t).is_ok(),
1398            &[],
1399        )
1400    }
1401
1402    /// A ULID (26 characters of Crockford's base 32).
1403    pub fn ulid(self) -> Self {
1404        self.text_rule("ulid", |t| t.trim().parse::<crate::db::Ulid>().is_ok(), &[])
1405    }
1406
1407    /// An IANA time zone name, e.g. `Asia/Jakarta`, or `UTC`.
1408    pub fn timezone(self) -> Self {
1409        self.text_rule(
1410            "timezone",
1411            |t| t.trim().parse::<chrono_tz::Tz>().is_ok(),
1412            &[],
1413        )
1414    }
1415
1416    /// A MAC address: `00:1A:2B:3C:4D:5E`, with `-` as well, or
1417    /// `001A.2B3C.4D5E`.
1418    pub fn mac_address(self) -> Self {
1419        self.text_rule("mac_address", is_mac_address, &[])
1420    }
1421
1422    /// ASCII characters only.
1423    pub fn ascii(self) -> Self {
1424        self.text_rule("ascii", |t| t.is_ascii(), &[])
1425    }
1426
1427    /// A hex colour: `#RGB`, `#RGBA`, `#RRGGBB` or `#RRGGBBAA`.
1428    pub fn hex_color(self) -> Self {
1429        self.text_rule(
1430            "hex_color",
1431            |t| {
1432                t.strip_prefix('#').is_some_and(|hex| {
1433                    matches!(hex.len(), 3 | 4 | 6 | 8) && hex.chars().all(|c| c.is_ascii_hexdigit())
1434                })
1435            },
1436            &[],
1437        )
1438    }
1439
1440    /// Doesn't start with any of `prefixes`.
1441    pub fn doesnt_start_with(self, prefixes: &[&str]) -> Self {
1442        let values = prefixes.join(", ");
1443        self.text_rule(
1444            "doesnt_start_with",
1445            |t| !prefixes.iter().any(|p| t.starts_with(p)),
1446            &[("values", values)],
1447        )
1448    }
1449
1450    /// Doesn't end with any of `suffixes`.
1451    pub fn doesnt_end_with(self, suffixes: &[&str]) -> Self {
1452        let values = suffixes.join(", ");
1453        self.text_rule(
1454            "doesnt_end_with",
1455            |t| !suffixes.iter().any(|s| t.ends_with(s)),
1456            &[("values", values)],
1457        )
1458    }
1459
1460    /// The text does not match `pattern` (Laravel's `not_regex`).
1461    pub fn not_matches(mut self, pattern: &str) -> Self {
1462        if let (true, Inspected::Text(text)) = (self.present(), &self.value) {
1463            let matched = match cached_regex(pattern) {
1464                Ok(regex) => regex.is_match(text),
1465                Err(err) => {
1466                    tracing::error!(pattern, error = %err, "invalid pattern in a `not_matches` rule");
1467                    true
1468                }
1469            };
1470            if matched {
1471                self.fail("not_regex", &[]);
1472            }
1473        }
1474        self
1475    }
1476
1477    /// A checkbox that must be ticked when `condition` holds.
1478    pub fn accepted_if(self, condition: bool) -> Self {
1479        if condition { self.accepted() } else { self }
1480    }
1481
1482    /// Must be declined: an unticked checkbox (`false`), or `no`, `off`,
1483    /// `0` or `false`, e.g. "Don't share my data" answered no.
1484    pub fn declined(mut self) -> Self {
1485        let declined = match &self.value {
1486            Inspected::Bool(b) => !b,
1487            Inspected::Number(n) => *n == 0.0,
1488            Inspected::Text(text) => {
1489                matches!(
1490                    text.trim().to_ascii_lowercase().as_str(),
1491                    "no" | "off" | "0" | "false"
1492                )
1493            }
1494            _ => false,
1495        };
1496        if !self.failed && !declined {
1497            self.fail("declined", &[]);
1498        }
1499        self
1500    }
1501
1502    /// Must be declined when `condition` holds; see [`declined`](Self::declined).
1503    pub fn declined_if(self, condition: bool) -> Self {
1504        if condition { self.declined() } else { self }
1505    }
1506
1507    /// The value meets `policy` (length, letters, mixed case, numbers,
1508    /// symbols); see [`Password`].
1509    pub fn password(mut self, policy: &Password) -> Self {
1510        if let (true, Inspected::Text(text)) = (self.present(), &self.value) {
1511            match policy.broken(text) {
1512                Some((key, params)) => self.fail(key, &params),
1513                None if policy.uncompromised => {
1514                    let text = text.clone();
1515                    self.check(AsyncKind::Uncompromised(text));
1516                }
1517                None => {}
1518            }
1519        }
1520        self
1521    }
1522
1523    /// The logged-in user's password (Laravel's `current_password`), e.g.
1524    /// before changing an email address. Checked last, once the other
1525    /// rules pass; it fails when no one is logged in. Needs
1526    /// [`Validator::finish_for`], which `Valid<T>` uses.
1527    pub fn current_password(mut self) -> Self {
1528        if let (true, Inspected::Text(text)) = (self.present(), &self.value) {
1529            let text = text.clone();
1530            self.check(AsyncKind::CurrentPassword(text));
1531        }
1532        self
1533    }
1534
1535    /// A reusable rule; see [`Rule`].
1536    pub fn apply(mut self, rule: &impl Rule) -> Self {
1537        if !self.present() {
1538            return self;
1539        }
1540        if let Err(message) = rule.check(&self.value) {
1541            let message = render(&message, &self.label, &[]);
1542            self.v.errors.add(&self.name, message);
1543            self.failed = true;
1544            self.last_pending = None;
1545            self.last_check = None;
1546        }
1547        self
1548    }
1549
1550    fn database(mut self, table: &str, column: &str, unique: bool) -> Self {
1551        if self.present() {
1552            self.v.pending.push(Pending {
1553                field: self.name.clone(),
1554                label: self.label.clone(),
1555                table: table.to_owned(),
1556                column: column.to_owned(),
1557                value: self.db_value.clone(),
1558                ignore_id: None,
1559                scope: Vec::new(),
1560                unique,
1561                message: None,
1562            });
1563            self.last_pending = Some(self.v.pending.len() - 1);
1564            self.last_check = None;
1565        }
1566        self
1567    }
1568
1569    /// No row in `table` has this value in `column`.
1570    pub fn unique(self, table: &str, column: &str) -> Self {
1571        self.database(table, column, true)
1572    }
1573
1574    /// Skips the row with this id in the preceding `unique`, for updates:
1575    /// `.unique("products", "sku").ignore(product.id)`, whatever the key's
1576    /// type (`i64`, `Ulid`, `Uuid`, `String`).
1577    pub fn ignore(self, id: impl crate::db::ToDbValue) -> Self {
1578        if let Some(i) = self.last_pending {
1579            self.v.pending[i].ignore_id = Some(id.to_db_value());
1580        }
1581        self
1582    }
1583
1584    /// Some row in `table` has this value in `column`.
1585    pub fn exists(self, table: &str, column: &str) -> Self {
1586        self.database(table, column, false)
1587    }
1588
1589    /// Only rows where `column = value` count for the preceding `unique` or
1590    /// `exists`, e.g. the current team's: SKUs are unique per team.
1591    ///
1592    /// ```
1593    /// # use renox::prelude::*;
1594    /// # struct ProductForm { id: i64, sku: String, category_id: i64, team_id: i64 }
1595    /// # impl Validate for ProductForm {
1596    /// fn rules(&self, v: &mut Validator) {
1597    ///     v.field("sku", &self.sku)
1598    ///         .unique("products", "sku")
1599    ///         .ignore(self.id)
1600    ///         .where_eq("team_id", self.team_id)
1601    ///         .where_null("deleted_at"); // soft-deleted rows don't count
1602    ///     v.field("category_id", &self.category_id)
1603    ///         .exists("categories", "id")
1604    ///         .where_eq("team_id", self.team_id); // not another team's category
1605    /// }
1606    /// # }
1607    /// ```
1608    pub fn where_eq(self, column: &str, value: impl ToDbValue) -> Self {
1609        self.scope(ScopeCondition::Eq(column.to_owned(), value.to_db_value()))
1610    }
1611
1612    /// Only rows where `column` is null count (e.g. `deleted_at`).
1613    pub fn where_null(self, column: &str) -> Self {
1614        self.scope(ScopeCondition::Null(column.to_owned()))
1615    }
1616
1617    /// Only rows where `column` is not null count.
1618    pub fn where_not_null(self, column: &str) -> Self {
1619        self.scope(ScopeCondition::NotNull(column.to_owned()))
1620    }
1621
1622    fn scope(self, condition: ScopeCondition) -> Self {
1623        if let Some(i) = self.last_pending {
1624            self.v.pending[i].scope.push(condition);
1625        }
1626        self
1627    }
1628}
1629
1630/// What a password must contain; `Field::password(&policy)` checks it.
1631/// The built-in register, reset and account forms use the app's policy
1632/// (`Auth::password_rules`), `Password::min(8)` by default.
1633///
1634/// ```
1635/// # use renox::prelude::*;
1636/// use renox::validation::Password;
1637/// # struct Form { password: String }
1638/// # impl Validate for Form {
1639/// fn rules(&self, v: &mut Validator) {
1640///     let policy = Password::min(12).mixed_case().numbers().symbols();
1641///     v.field("password", &self.password).required().password(&policy);
1642/// }
1643/// # }
1644/// ```
1645#[derive(Debug, Clone, PartialEq, Eq)]
1646pub struct Password {
1647    min: usize,
1648    letters: bool,
1649    mixed_case: bool,
1650    numbers: bool,
1651    symbols: bool,
1652    uncompromised: bool,
1653}
1654
1655impl Password {
1656    /// At least `min` characters.
1657    pub fn min(min: usize) -> Self {
1658        Self {
1659            min,
1660            letters: false,
1661            mixed_case: false,
1662            numbers: false,
1663            symbols: false,
1664            uncompromised: false,
1665        }
1666    }
1667
1668    /// Not a password found in a known data breach (Laravel's
1669    /// `uncompromised`), checked with Have I Been Pwned: only the first
1670    /// five characters of the password's SHA-1 leave the server
1671    /// (k-anonymity), through `state.http` (faked in tests). When the
1672    /// service can't be reached the password is allowed and a warning
1673    /// logged. Runs once the other rules pass.
1674    pub fn uncompromised(mut self) -> Self {
1675        self.uncompromised = true;
1676        self
1677    }
1678
1679    /// At least one letter.
1680    pub fn letters(mut self) -> Self {
1681        self.letters = true;
1682        self
1683    }
1684
1685    /// At least one uppercase and one lowercase letter.
1686    pub fn mixed_case(mut self) -> Self {
1687        self.mixed_case = true;
1688        self
1689    }
1690
1691    /// At least one digit.
1692    pub fn numbers(mut self) -> Self {
1693        self.numbers = true;
1694        self
1695    }
1696
1697    /// At least one character that isn't a letter, digit or space.
1698    pub fn symbols(mut self) -> Self {
1699        self.symbols = true;
1700        self
1701    }
1702
1703    /// The first rule `password` breaks: a message key and its parameters.
1704    fn broken(&self, password: &str) -> Option<(&'static str, Vec<(&'static str, String)>)> {
1705        if password.chars().count() < self.min {
1706            return Some(("min.string", vec![("min", self.min.to_string())]));
1707        }
1708        let has = |test: fn(&char) -> bool| password.chars().any(|c| test(&c));
1709        if self.letters && !has(|c| c.is_alphabetic()) {
1710            return Some(("password.letters", Vec::new()));
1711        }
1712        if self.mixed_case && !(has(|c| c.is_uppercase()) && has(|c| c.is_lowercase())) {
1713            return Some(("password.mixed", Vec::new()));
1714        }
1715        if self.numbers && !has(|c| c.is_numeric()) {
1716            return Some(("password.numbers", Vec::new()));
1717        }
1718        if self.symbols && !has(|c| !c.is_alphanumeric() && !c.is_whitespace()) {
1719            return Some(("password.symbols", Vec::new()));
1720        }
1721        None
1722    }
1723}
1724
1725impl Default for Password {
1726    fn default() -> Self {
1727        Self::min(8)
1728    }
1729}
1730
1731/// A rule to reuse across forms, e.g. a tax number:
1732///
1733/// ```
1734/// # use renox::prelude::*;
1735/// use renox::validation::{Inspected, Rule};
1736///
1737/// struct TaxId;
1738///
1739/// impl Rule for TaxId {
1740///     fn check(&self, value: &Inspected) -> std::result::Result<(), String> {
1741///         let Inspected::Text(text) = value else { return Ok(()) };
1742///         let digits = text.chars().filter(char::is_ascii_digit).count();
1743///         if digits == 15 || digits == 16 {
1744///             Ok(())
1745///         } else {
1746///             Err("The :attribute must be a valid tax ID.".into()) // :attribute is the field's label
1747///         }
1748///     }
1749/// }
1750///
1751/// # struct Form { tax_id: String }
1752/// # impl Validate for Form {
1753/// fn rules(&self, v: &mut Validator) {
1754///     v.field("tax_id", &self.tax_id).required().apply(&TaxId);
1755/// }
1756/// # }
1757/// ```
1758///
1759/// Missing values skip the rule (combine it with `required`).
1760pub trait Rule {
1761    /// `Err(message)` when `value` breaks the rule.
1762    fn check(&self, value: &Inspected) -> std::result::Result<(), String>;
1763}
1764
1765/// Limits for an uploaded image's size in pixels, for
1766/// [`Field::dimensions`] (Laravel's `dimensions`).
1767///
1768/// ```
1769/// # use renox::prelude::*;
1770/// use renox::validation::Dimensions;
1771/// # struct Form { banner: Option<Upload> }
1772/// # impl Validate for Form {
1773/// fn rules(&self, v: &mut Validator) {
1774///     let banner = Dimensions::new().min_width(1200).ratio(3, 1);
1775///     v.field("banner", &self.banner).image().dimensions(&banner);
1776/// }
1777/// # }
1778/// ```
1779#[derive(Debug, Clone, Default, PartialEq)]
1780pub struct Dimensions {
1781    min_width: Option<u32>,
1782    max_width: Option<u32>,
1783    min_height: Option<u32>,
1784    max_height: Option<u32>,
1785    width: Option<u32>,
1786    height: Option<u32>,
1787    ratio: Option<(u32, u32)>,
1788}
1789
1790impl Dimensions {
1791    /// No limits yet.
1792    pub fn new() -> Self {
1793        Self::default()
1794    }
1795
1796    /// At least `px` wide.
1797    pub fn min_width(mut self, px: u32) -> Self {
1798        self.min_width = Some(px);
1799        self
1800    }
1801
1802    /// At most `px` wide.
1803    pub fn max_width(mut self, px: u32) -> Self {
1804        self.max_width = Some(px);
1805        self
1806    }
1807
1808    /// At least `px` high.
1809    pub fn min_height(mut self, px: u32) -> Self {
1810        self.min_height = Some(px);
1811        self
1812    }
1813
1814    /// At most `px` high.
1815    pub fn max_height(mut self, px: u32) -> Self {
1816        self.max_height = Some(px);
1817        self
1818    }
1819
1820    /// Exactly `px` wide.
1821    pub fn width(mut self, px: u32) -> Self {
1822        self.width = Some(px);
1823        self
1824    }
1825
1826    /// Exactly `px` high.
1827    pub fn height(mut self, px: u32) -> Self {
1828        self.height = Some(px);
1829        self
1830    }
1831
1832    /// Width to height in this ratio, e.g. `ratio(16, 9)` or `ratio(1, 1)`
1833    /// for a square (to within a pixel of rounding).
1834    pub fn ratio(mut self, width: u32, height: u32) -> Self {
1835        self.ratio = Some((width, height));
1836        self
1837    }
1838
1839    fn allows(&self, w: u32, h: u32) -> bool {
1840        let at_least = |limit: Option<u32>, v: u32| limit.is_none_or(|l| v >= l);
1841        let at_most = |limit: Option<u32>, v: u32| limit.is_none_or(|l| v <= l);
1842        let exactly = |limit: Option<u32>, v: u32| limit.is_none_or(|l| v == l);
1843        let ratio = self.ratio.is_none_or(|(rw, rh)| {
1844            // Within one pixel of the exact height for this width.
1845            rw > 0 && (h as f64 - w as f64 * rh as f64 / rw as f64).abs() <= 1.0
1846        });
1847        at_least(self.min_width, w)
1848            && at_most(self.max_width, w)
1849            && at_least(self.min_height, h)
1850            && at_most(self.max_height, h)
1851            && exactly(self.width, w)
1852            && exactly(self.height, h)
1853            && ratio
1854    }
1855}
1856
1857/// The Have I Been Pwned range API (`app.fake_http()` answers it in tests).
1858const PWNED_RANGE: &str = "https://api.pwnedpasswords.com/range/";
1859
1860/// Whether `password` appears in a known breach. Errors (no network, a
1861/// slow service) count as "no", with a warning, so sign-ups keep working.
1862async fn breached(state: &crate::AppState, password: &str) -> bool {
1863    use sha1::{Digest, Sha1};
1864    let hash: String = Sha1::digest(password.as_bytes())
1865        .iter()
1866        .map(|b| format!("{b:02X}"))
1867        .collect();
1868    let (prefix, suffix) = hash.split_at(5);
1869    let response = state
1870        .http
1871        .get(format!("{PWNED_RANGE}{prefix}"))
1872        .header("Add-Padding", "true")
1873        .timeout(std::time::Duration::from_secs(5))
1874        .send()
1875        .await;
1876    match response {
1877        Ok(response) if response.status().is_success() => response.text().lines().any(|line| {
1878            line.split_once(':').is_some_and(|(candidate, count)| {
1879                candidate.trim().eq_ignore_ascii_case(suffix)
1880                    && count.trim().parse::<u64>().is_ok_and(|n| n > 0)
1881            })
1882        }),
1883        Ok(response) => {
1884            tracing::warn!(status = %response.status(), "the password breach check answered with an error; allowing the password");
1885            false
1886        }
1887        Err(err) => {
1888            tracing::warn!(error = ?err, "the password breach check failed; allowing the password");
1889            false
1890        }
1891    }
1892}
1893
1894/// Decimal places of a plain decimal number (`12`, `-3.50`), else `None`.
1895fn decimal_places(text: &str) -> Option<usize> {
1896    let digits = text.strip_prefix(['-', '+']).unwrap_or(text);
1897    let (whole, fraction) = digits.split_once('.').unwrap_or((digits, ""));
1898    let all_digits = |s: &str| s.chars().all(|c| c.is_ascii_digit());
1899    (!whole.is_empty()
1900        && all_digits(whole)
1901        && all_digits(fraction)
1902        && !(digits.contains('.') && fraction.is_empty()))
1903    .then_some(fraction.len())
1904}
1905
1906/// The date a date rule compares with: a date value, or text that reads as
1907/// one (`"2026-01-01"`). Anything else leaves the rule out.
1908fn limit_date(limit: &impl FieldValue) -> Option<NaiveDateTime> {
1909    match limit.inspect() {
1910        Inspected::Date(date) => Some(date),
1911        Inspected::Text(text) => parse_date(text.trim()),
1912        _ => None,
1913    }
1914}
1915
1916/// The value as a number: a number, or text that reads as a finite one.
1917fn numeric_value(value: &Inspected) -> Option<f64> {
1918    match value {
1919        Inspected::Number(n) => Some(*n),
1920        Inspected::Text(text) => {
1921            let text = text.trim();
1922            decimal_places(text)?;
1923            text.parse::<f64>().ok().filter(|n| n.is_finite())
1924        }
1925        _ => None,
1926    }
1927}
1928
1929/// How many digits an integer value has (the sign doesn't count).
1930fn integer_digits(value: &Inspected) -> Option<usize> {
1931    let n = numeric_value(value)?;
1932    (n.fract() == 0.0).then(|| format!("{}", n.abs() as u64).len())
1933}
1934
1935fn is_mac_address(text: &str) -> bool {
1936    let text = text.trim();
1937    let hex = |s: &str, n: usize| s.len() == n && s.chars().all(|c| c.is_ascii_hexdigit());
1938    for separator in [':', '-'] {
1939        let parts: Vec<&str> = text.split(separator).collect();
1940        if parts.len() == 6 && parts.iter().all(|p| hex(p, 2)) {
1941            return true;
1942        }
1943    }
1944    let parts: Vec<&str> = text.split('.').collect();
1945    parts.len() == 3 && parts.iter().all(|p| hex(p, 4))
1946}
1947
1948fn is_uuid(text: &str) -> bool {
1949    let groups: Vec<&str> = text.trim().split('-').collect();
1950    groups.len() == 5
1951        && groups
1952            .iter()
1953            .zip([8, 4, 4, 4, 12])
1954            .all(|(g, n)| g.len() == n && g.chars().all(|c| c.is_ascii_hexdigit()))
1955}
1956
1957/// Compiled patterns, so a rule in a hot form doesn't recompile each time.
1958fn cached_regex(pattern: &str) -> std::result::Result<regex::Regex, regex::Error> {
1959    static CACHE: std::sync::LazyLock<
1960        std::sync::Mutex<std::collections::HashMap<String, regex::Regex>>,
1961    > = std::sync::LazyLock::new(Default::default);
1962    let mut cache = CACHE.lock().unwrap_or_else(|e| e.into_inner());
1963    if let Some(regex) = cache.get(pattern) {
1964        return Ok(regex.clone());
1965    }
1966    let regex = regex::Regex::new(pattern)?;
1967    if cache.len() < 1000 {
1968        cache.insert(pattern.to_owned(), regex.clone());
1969    }
1970    Ok(regex)
1971}
1972
1973/// How many digits the value is made of, if it's only digits.
1974fn digit_count(value: &Inspected) -> Option<usize> {
1975    let text = match value {
1976        Inspected::Text(text) => text.trim().to_owned(),
1977        Inspected::Number(n) if n.fract() == 0.0 && *n >= 0.0 => format!("{}", *n as u64),
1978        _ => return None,
1979    };
1980    (!text.is_empty() && text.chars().all(|c| c.is_ascii_digit())).then_some(text.len())
1981}
1982
1983/// `2026-10-01`, `2026-10-01T10:30`, `2026-10-01 10:30:00` or RFC 3339.
1984fn parse_date(text: &str) -> Option<NaiveDateTime> {
1985    if let Ok(date) = chrono::NaiveDate::parse_from_str(text, "%Y-%m-%d") {
1986        return Some(date.and_time(chrono::NaiveTime::MIN));
1987    }
1988    for format in [
1989        "%Y-%m-%dT%H:%M",
1990        "%Y-%m-%dT%H:%M:%S",
1991        "%Y-%m-%d %H:%M",
1992        "%Y-%m-%d %H:%M:%S",
1993    ] {
1994        if let Ok(date) = NaiveDateTime::parse_from_str(text, format) {
1995            return Some(date);
1996        }
1997    }
1998    chrono::DateTime::parse_from_rfc3339(text)
1999        .ok()
2000        .map(|d| d.naive_utc())
2001}
2002
2003fn is_email(text: &str) -> bool {
2004    let Some((local, domain)) = text.split_once('@') else {
2005        return false;
2006    };
2007    !local.is_empty()
2008        && !text.chars().any(char::is_whitespace)
2009        && !domain.contains('@')
2010        && domain.contains('.')
2011        && domain.split('.').all(|part| !part.is_empty())
2012}
2013
2014fn is_url(text: &str) -> bool {
2015    let rest = text
2016        .strip_prefix("https://")
2017        .or_else(|| text.strip_prefix("http://"));
2018    matches!(rest, Some(rest) if !rest.is_empty()
2019        && !rest.starts_with('/')
2020        && !text.chars().any(char::is_whitespace))
2021}
2022
2023/// Keys never flashed back into forms.
2024const DONT_FLASH: &[&str] = &[
2025    "password",
2026    "password_confirmation",
2027    "current_password",
2028    "_token",
2029];
2030
2031/// A failed validation. As a response it is `422` with
2032/// `{"message": ..., "errors": {...}}`; for regular (non-HTMX, non-JSON)
2033/// requests Renox turns it into a redirect back with the errors and old
2034/// input flashed to the session.
2035///
2036/// Return it from a handler for errors found after validation:
2037///
2038/// ```
2039/// # use renox::prelude::*;
2040/// # #[derive(serde::Serialize)] struct StockForm { quantity: i64 }
2041/// # fn demo(form: StockForm) -> Result {
2042/// let mut errors = Errors::new();
2043/// errors.add("quantity", "Not enough stock.");
2044/// return Err(ValidationError::new(errors).with_input(&form).into());
2045/// # }
2046/// ```
2047#[derive(Debug, Clone)]
2048pub struct ValidationError {
2049    /// The messages, keyed by field name.
2050    pub errors: Errors,
2051    /// The submitted values flashed back into the form (never passwords).
2052    pub input: Map<String, Value>,
2053    /// The named error bag (`in_bag`), for a page with several forms.
2054    bag: Option<String>,
2055}
2056
2057impl ValidationError {
2058    /// An error with these messages and no input to refill.
2059    pub fn new(errors: Errors) -> Self {
2060        Self {
2061            errors,
2062            input: Map::new(),
2063            bag: None,
2064        }
2065    }
2066
2067    /// Flashes the errors in the named bag `bag` (Laravel's error bags) when
2068    /// the form is sent back: the page shows them with
2069    /// `error('email', bag='login')`, and the default `error('email')` of
2070    /// another form on the page stays empty. `Valid<T>` does it for
2071    /// [`Validate::ERROR_BAG`].
2072    pub fn in_bag(mut self, bag: impl Into<String>) -> Self {
2073        self.bag = Some(bag.into());
2074        self
2075    }
2076
2077    /// The named error bag, if any.
2078    pub fn bag(&self) -> Option<&str> {
2079        self.bag.as_deref()
2080    }
2081
2082    /// The submitted values to refill the form with (passwords are dropped).
2083    pub fn with_input(mut self, input: &impl Serialize) -> Self {
2084        if let Ok(Value::Object(map)) = serde_json::to_value(input) {
2085            self.input = map;
2086        }
2087        self.input
2088            .retain(|key, _| !DONT_FLASH.contains(&key.as_str()));
2089        self
2090    }
2091
2092    pub(crate) fn with_input_map(mut self, input: Map<String, Value>) -> Self {
2093        self.input = input;
2094        self.input
2095            .retain(|key, _| !DONT_FLASH.contains(&key.as_str()));
2096        self
2097    }
2098}
2099
2100impl From<Errors> for ValidationError {
2101    fn from(errors: Errors) -> Self {
2102        Self::new(errors)
2103    }
2104}
2105
2106impl IntoResponse for ValidationError {
2107    fn into_response(self) -> Response {
2108        let message = self
2109            .errors
2110            .iter()
2111            .next()
2112            .and_then(|(_, m)| m.first().cloned())
2113            .unwrap_or_default();
2114        let body = json!({ "message": message, "errors": self.errors });
2115        let mut res = (StatusCode::UNPROCESSABLE_ENTITY, axum::Json(body)).into_response();
2116        res.extensions_mut().insert(self);
2117        res
2118    }
2119}
2120
2121#[cfg(test)]
2122mod tests {
2123    use super::*;
2124
2125    #[test]
2126    fn checks_emails_and_urls() {
2127        assert!(is_email("alex@example.com"));
2128        assert!(!is_email("alex@localhost"));
2129        assert!(!is_email("alex example@x.com"));
2130        assert!(!is_email("@x.com"));
2131        assert!(is_url("https://renox.dev/docs"));
2132        assert!(!is_url("ftp://renox.dev"));
2133        assert!(!is_url("https://"));
2134    }
2135
2136    #[test]
2137    fn formats_numbers_without_trailing_zeros() {
2138        assert_eq!(number(3.0), "3");
2139        assert_eq!(number(2.5), "2.5");
2140    }
2141    /// A value that inspects as whatever a test needs (a file, a bool).
2142    struct As(Inspected);
2143
2144    impl FieldValue for As {
2145        fn inspect(&self) -> Inspected {
2146            self.0.clone()
2147        }
2148        fn db_value(&self) -> DbValue {
2149            DbValue::Null
2150        }
2151    }
2152
2153    /// A rule that fails every value it sees.
2154    struct Never;
2155
2156    impl Rule for Never {
2157        fn check(&self, _: &Inspected) -> std::result::Result<(), String> {
2158            Err("never".into())
2159        }
2160    }
2161
2162    fn file(kilobytes: f64, dimensions: Option<(u32, u32)>) -> As {
2163        As(Inspected::File {
2164            kilobytes,
2165            extension: "png".into(),
2166            image: true,
2167            dimensions,
2168        })
2169    }
2170
2171    // #250: the branches rules take for values they don't measure, and the
2172    // passing side of rules only failures had reached.
2173    #[test]
2174    fn rules_pass_or_step_aside_for_values_they_dont_judge() {
2175        let mut v = Validator::default();
2176        let photo = file(120.0, Some((800, 600)));
2177        v.field("photo", &photo)
2178            .mimes(&["PNG", "jpeg"])
2179            .dimensions(&Dimensions::new().min_width(400).max_height(600));
2180        v.field("code", &"AB1234")
2181            .matches(r"^[A-Z]{2}\d{4}$")
2182            .not_matches(r"^\d+$");
2183        v.field("secret", &"long enough password")
2184            .password(&Password::min(8));
2185        // Rules that can't read the value leave it alone.
2186        let missing: Option<String> = None;
2187        v.field("note", &missing)
2188            .decimal(2, 2)
2189            .apply(&Never)
2190            .gt("other", &"5");
2191        v.field("price", &"12").gt("budget", &missing);
2192        // A limit that isn't a date leaves the date rules out.
2193        v.field("day", &"2026-01-01")
2194            .before_or_equal(5)
2195            .after(true)
2196            .after_or_equal(2.5);
2197        assert!(v.errors.is_empty(), "{:?}", v.errors);
2198    }
2199
2200    #[test]
2201    fn rules_fail_values_of_the_wrong_kind() {
2202        let mut v = Validator::default();
2203        // A number isn't a date; a bool has no digits, no decimals, no number.
2204        v.field("day", &7).before("2026-01-01");
2205        v.field("agree", &true).digits(3);
2206        v.field("flag", &true).decimal(2, 2);
2207        v.field("on", &true).numeric();
2208        // Two files compare by size; two booleans can't be compared.
2209        v.field("photo", &file(10.0, None))
2210            .gt("thumb", &file(20.0, None));
2211        v.field("yes", &true).lt("no", &false);
2212        assert_eq!(v.errors.first("day"), Some("The day is not a valid date."));
2213        assert_eq!(v.errors.first("agree"), Some("The agree must be 3 digits."));
2214        assert_eq!(
2215            v.errors.first("flag"),
2216            Some("The flag must have 2 decimal places.")
2217        );
2218        assert_eq!(v.errors.first("on"), Some("The on must be a number."));
2219        assert_eq!(
2220            v.errors.first("photo"),
2221            Some("The photo must be larger than thumb.")
2222        );
2223        assert!(v.errors.has("yes"), "{:?}", v.errors);
2224        // An image too wide fails `dimensions`.
2225        let mut v = Validator::new();
2226        v.field("photo", &file(1.0, Some((2000, 10))))
2227            .dimensions(&Dimensions::new().max_width(100));
2228        assert!(v.errors.has("photo"));
2229    }
2230
2231    #[test]
2232    fn geo_rules_check_ranges_and_point_shapes() {
2233        let mut v = Validator::default();
2234        v.field("lat", &"25.2048").latitude();
2235        v.field("lat_n", &-90.0).latitude();
2236        v.field("lng", &" -180 ").longitude();
2237        v.field("here", &r#"{"lat": 25.2, "lng": 55.3}"#).point();
2238        v.field("geo", &r#"{"type":"Point","coordinates":[55.3,25.2]}"#)
2239            .point();
2240        v.field("empty", &"").point();
2241        assert!(v.errors.is_empty(), "{:?}", v.errors);
2242
2243        let mut v = Validator::default();
2244        v.field("lat", &"91").latitude();
2245        v.field("lat_text", &"north").latitude();
2246        v.field("lng", &181.5).longitude();
2247        v.field("nan", &f64::NAN).longitude();
2248        v.field("p_lat", &r#"{"lat": 95, "lng": 0}"#).point();
2249        v.field("p_lng", &r#"{"type":"Point","coordinates":[200,0]}"#)
2250            .point();
2251        v.field("p_junk", &"25.2, 55.3").point();
2252        v.field("p_half", &r#"{"lat": 1}"#).point();
2253        assert_eq!(
2254            v.errors.first("lat"),
2255            Some("The lat must be a latitude between -90 and 90.")
2256        );
2257        assert!(v.errors.has("lat_text"));
2258        assert_eq!(
2259            v.errors.first("lng"),
2260            Some("The lng must be a longitude between -180 and 180.")
2261        );
2262        assert!(v.errors.has("nan"));
2263        assert_eq!(
2264            v.errors.first("p_lat"),
2265            Some("The p lat must be a latitude between -90 and 90.")
2266        );
2267        assert_eq!(
2268            v.errors.first("p_lng"),
2269            Some("The p lng must be a longitude between -180 and 180.")
2270        );
2271        for field in ["p_junk", "p_half"] {
2272            assert!(
2273                v.errors.first(field).unwrap().contains("valid point"),
2274                "{field}"
2275            );
2276        }
2277    }
2278
2279    #[test]
2280    fn nested_rows_carry_their_async_checks_under_the_row_name() {
2281        struct Row {
2282            password: String,
2283        }
2284        impl Validate for Row {
2285            fn rules(&self, v: &mut Validator) {
2286                v.field("password", &self.password).current_password();
2287            }
2288        }
2289        let mut v = Validator::new();
2290        v.nested(
2291            "rows",
2292            &[
2293                Row {
2294                    password: "a".into(),
2295                },
2296                Row {
2297                    password: "b".into(),
2298                },
2299            ],
2300        );
2301        let fields: Vec<_> = v.checks.iter().map(|c| c.field.as_str()).collect();
2302        assert_eq!(fields, ["rows.0.password", "rows.1.password"]);
2303    }
2304
2305    #[tokio::test]
2306    async fn checks_on_a_field_that_already_failed_are_skipped() {
2307        let db = crate::db::connect(&crate::Config::default()).await.unwrap();
2308        let mut v = Validator::new();
2309        // The field failed a rule before its database and async checks were
2310        // added: neither runs (no `users` table is asked), one error stays.
2311        v.field("email", &"not an email").email();
2312        v.field("email", &"not an email")
2313            .unique("no_such_table", "email")
2314            .current_password();
2315        // `.message` after an async check is that check's message.
2316        v.field("password", &"guess")
2317            .current_password()
2318            .message("That isn't your password.");
2319        let errors = v.finish(&db).await.unwrap();
2320        assert_eq!(
2321            errors.first("email"),
2322            Some("The email must be a valid email address.")
2323        );
2324        assert_eq!(
2325            errors.iter().find(|(f, _)| *f == "email").unwrap().1.len(),
2326            1
2327        );
2328        assert_eq!(errors.first("password"), Some("That isn't your password."));
2329    }
2330}