1pub(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#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
54#[serde(transparent)]
55pub struct Errors(BTreeMap<String, Vec<String>>);
56
57impl Errors {
58 pub fn new() -> Self {
60 Self::default()
61 }
62
63 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 pub fn is_empty(&self) -> bool {
70 self.0.is_empty()
71 }
72
73 pub fn has(&self, field: &str) -> bool {
75 self.0.contains_key(field)
76 }
77
78 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 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
92pub trait Validate {
134 const ERROR_BAG: Option<&'static str> = None;
140
141 fn rules(&self, v: &mut Validator);
143
144 fn prepare(&mut self) {}
148
149 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 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
173pub trait ValidateHooks {
200 fn prepare(&mut self) {}
202
203 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 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#[non_exhaustive]
226pub struct FormContext<'a> {
227 pub state: &'a crate::AppState,
229 pub user: Option<&'a crate::auth::User>,
231 pub method: &'a axum::http::Method,
233 pub path: &'a str,
235 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 scope: Vec<ScopeCondition>,
248 unique: bool,
249 message: Option<String>,
250}
251
252struct AsyncCheck {
254 field: String,
255 label: String,
256 kind: AsyncKind,
257 message: Option<String>,
258}
259
260enum AsyncKind {
261 CurrentPassword(String),
263 Uncompromised(String),
265}
266
267enum 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
282async 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
299pub struct Validator {
302 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 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 pub fn in_lang(self, lang: &crate::Lang) -> Self {
330 self.with_texts(lang.texts())
331 }
332
333 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 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 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 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 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 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 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 if let Inspected::Number(n) = field.value
456 && !n.is_finite()
457 {
458 field.fail("numeric", &[]);
459 }
460 field
461 }
462
463 pub fn error(&mut self, field: &str, message: impl Into<String>) {
465 self.errors.add(field, message);
466 }
467
468 pub async fn finish(self, db: &Db) -> Result<Errors> {
473 self.finish_with(db, None, None).await
474 }
475
476 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 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 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 pub fn rules_of(data: &impl Validate) -> Self {
598 let mut validator = Self::new();
599 data.rules(&mut validator);
600 validator
601 }
602}
603
604pub struct Field<'v> {
606 v: &'v mut Validator,
607 name: String,
608 label: String,
609 translated: bool,
611 value: Inspected,
612 db_value: DbValue,
613 failed: bool,
614 last_pending: Option<usize>,
615 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 pub fn label(mut self, label: &str) -> Self {
630 self.label = label.to_owned();
631 self
632 }
633
634 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 pub fn alpha(self) -> Self {
961 self.text_rule("alpha", |t| t.chars().all(char::is_alphabetic), &[])
962 }
963
964 pub fn alpha_num(self) -> Self {
966 self.text_rule("alpha_num", |t| t.chars().all(char::is_alphanumeric), &[])
967 }
968
969 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 pub fn lowercase(self) -> Self {
983 self.text_rule("lowercase", |t| !t.chars().any(char::is_uppercase), &[])
984 }
985
986 pub fn uppercase(self) -> Self {
988 self.text_rule("uppercase", |t| !t.chars().any(char::is_lowercase), &[])
989 }
990
991 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 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 pub fn uuid(self) -> Self {
1013 self.text_rule("uuid", is_uuid, &[])
1014 }
1015
1016 pub fn ip(self) -> Self {
1018 self.text_rule("ip", |t| t.trim().parse::<std::net::IpAddr>().is_ok(), &[])
1019 }
1020
1021 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 pub fn required_without(self, other: &impl FieldValue) -> Self {
1030 let missing = other.inspect() == Inspected::Missing;
1031 self.required_if(missing)
1032 }
1033
1034 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 pub fn required_if(self, condition: bool) -> Self {
1046 if condition { self.required() } else { self }
1047 }
1048
1049 pub fn required_unless(self, condition: bool) -> Self {
1051 self.required_if(!condition)
1052 }
1053
1054 pub fn required_with(self, other: &impl FieldValue) -> Self {
1057 let given = other.inspect() != Inspected::Missing;
1058 self.required_if(given)
1059 }
1060
1061 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 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 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 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 pub fn gt(self, other: &str, value: &impl FieldValue) -> Self {
1141 self.compare_rule("gt", other, value, |o| o.is_gt())
1142 }
1143
1144 pub fn gte(self, other: &str, value: &impl FieldValue) -> Self {
1146 self.compare_rule("gte", other, value, |o| o.is_ge())
1147 }
1148
1149 pub fn lt(self, other: &str, value: &impl FieldValue) -> Self {
1151 self.compare_rule("lt", other, value, |o| o.is_lt())
1152 }
1153
1154 pub fn lte(self, other: &str, value: &impl FieldValue) -> Self {
1156 self.compare_rule("lte", other, value, |o| o.is_le())
1157 }
1158
1159 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 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 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 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 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 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 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 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 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 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 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 pub fn prohibited(self) -> Self {
1312 self.prohibited_if(true)
1313 }
1314
1315 pub fn prohibited_unless(self, condition: bool) -> Self {
1317 self.prohibited_if(!condition)
1318 }
1319
1320 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 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 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 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 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 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 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 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 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 pub fn ulid(self) -> Self {
1404 self.text_rule("ulid", |t| t.trim().parse::<crate::db::Ulid>().is_ok(), &[])
1405 }
1406
1407 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 pub fn mac_address(self) -> Self {
1419 self.text_rule("mac_address", is_mac_address, &[])
1420 }
1421
1422 pub fn ascii(self) -> Self {
1424 self.text_rule("ascii", |t| t.is_ascii(), &[])
1425 }
1426
1427 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 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 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 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 pub fn accepted_if(self, condition: bool) -> Self {
1479 if condition { self.accepted() } else { self }
1480 }
1481
1482 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 pub fn declined_if(self, condition: bool) -> Self {
1504 if condition { self.declined() } else { self }
1505 }
1506
1507 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, ¶ms),
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 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 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 pub fn unique(self, table: &str, column: &str) -> Self {
1571 self.database(table, column, true)
1572 }
1573
1574 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 pub fn exists(self, table: &str, column: &str) -> Self {
1586 self.database(table, column, false)
1587 }
1588
1589 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 pub fn where_null(self, column: &str) -> Self {
1614 self.scope(ScopeCondition::Null(column.to_owned()))
1615 }
1616
1617 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#[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 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 pub fn uncompromised(mut self) -> Self {
1675 self.uncompromised = true;
1676 self
1677 }
1678
1679 pub fn letters(mut self) -> Self {
1681 self.letters = true;
1682 self
1683 }
1684
1685 pub fn mixed_case(mut self) -> Self {
1687 self.mixed_case = true;
1688 self
1689 }
1690
1691 pub fn numbers(mut self) -> Self {
1693 self.numbers = true;
1694 self
1695 }
1696
1697 pub fn symbols(mut self) -> Self {
1699 self.symbols = true;
1700 self
1701 }
1702
1703 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
1731pub trait Rule {
1761 fn check(&self, value: &Inspected) -> std::result::Result<(), String>;
1763}
1764
1765#[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 pub fn new() -> Self {
1793 Self::default()
1794 }
1795
1796 pub fn min_width(mut self, px: u32) -> Self {
1798 self.min_width = Some(px);
1799 self
1800 }
1801
1802 pub fn max_width(mut self, px: u32) -> Self {
1804 self.max_width = Some(px);
1805 self
1806 }
1807
1808 pub fn min_height(mut self, px: u32) -> Self {
1810 self.min_height = Some(px);
1811 self
1812 }
1813
1814 pub fn max_height(mut self, px: u32) -> Self {
1816 self.max_height = Some(px);
1817 self
1818 }
1819
1820 pub fn width(mut self, px: u32) -> Self {
1822 self.width = Some(px);
1823 self
1824 }
1825
1826 pub fn height(mut self, px: u32) -> Self {
1828 self.height = Some(px);
1829 self
1830 }
1831
1832 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 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
1857const PWNED_RANGE: &str = "https://api.pwnedpasswords.com/range/";
1859
1860async 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
1894fn 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
1906fn 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
1916fn 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
1929fn 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
1957fn 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
1973fn 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
1983fn 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
2023const DONT_FLASH: &[&str] = &[
2025 "password",
2026 "password_confirmation",
2027 "current_password",
2028 "_token",
2029];
2030
2031#[derive(Debug, Clone)]
2048pub struct ValidationError {
2049 pub errors: Errors,
2051 pub input: Map<String, Value>,
2053 bag: Option<String>,
2055}
2056
2057impl ValidationError {
2058 pub fn new(errors: Errors) -> Self {
2060 Self {
2061 errors,
2062 input: Map::new(),
2063 bag: None,
2064 }
2065 }
2066
2067 pub fn in_bag(mut self, bag: impl Into<String>) -> Self {
2073 self.bag = Some(bag.into());
2074 self
2075 }
2076
2077 pub fn bag(&self) -> Option<&str> {
2079 self.bag.as_deref()
2080 }
2081
2082 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 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 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 #[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 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 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 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 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 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 v.field("email", &"not an email").email();
2312 v.field("email", &"not an email")
2313 .unique("no_such_table", "email")
2314 .current_password();
2315 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}