1use regex::Regex;
37use serde_json::Value;
38use std::collections::HashMap;
39use std::fmt;
40use std::sync::OnceLock;
41
42pub mod codes {
44 pub const REQUIRED: &str = "required";
45 pub const UNKNOWN_FIELD: &str = "unknown_field";
46 pub const TYPE: &str = "type";
47 pub const MIN_LENGTH: &str = "min_length";
48 pub const MAX_LENGTH: &str = "max_length";
49 pub const MIN_VALUE: &str = "min_value";
50 pub const MAX_VALUE: &str = "max_value";
51 pub const PATTERN: &str = "pattern";
52 pub const CHOICES: &str = "choices";
53 pub const EMAIL: &str = "email";
54 pub const URL: &str = "url";
55 pub const CUSTOM: &str = "custom";
56 pub const UUID: &str = "uuid";
57 pub const DATE: &str = "date";
58 pub const DATETIME: &str = "datetime";
59 pub const NUMERIC: &str = "numeric";
60 pub const NOT_EMPTY: &str = "not_empty";
61 pub const ENUM: &str = "enum";
62 pub const ONE_OF: &str = "one_of";
63}
64
65#[derive(Debug, Clone)]
67pub struct ValidationError {
68 pub field: String,
69 pub message: String,
70 pub code: String,
71 pub value: Option<Value>,
72}
73
74impl ValidationError {
75 pub fn new(field: impl Into<String>, message: impl Into<String>) -> Self {
77 Self {
78 field: field.into(),
79 message: message.into(),
80 code: String::new(),
81 value: None,
82 }
83 }
84
85 pub fn with_code(mut self, code: impl Into<String>) -> Self {
87 self.code = code.into();
88 self
89 }
90
91 pub fn with_value(mut self, value: impl Into<Option<Value>>) -> Self {
96 self.value = value.into();
97 self
98 }
99}
100
101impl fmt::Display for ValidationError {
102 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103 write!(f, "{}: {}", self.field, self.message)
104 }
105}
106
107impl std::error::Error for ValidationError {}
108
109#[derive(Debug, Clone)]
113pub struct ValidationErrors(pub Vec<ValidationError>);
114
115impl fmt::Display for ValidationErrors {
116 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117 for (i, error) in self.0.iter().enumerate() {
118 if i > 0 {
119 writeln!(f)?;
120 }
121 write!(f, "{error}")?;
122 }
123 Ok(())
124 }
125}
126
127impl std::error::Error for ValidationErrors {}
128
129#[derive(Debug, Clone, Default)]
131pub struct ValidationResult {
132 errors: Vec<ValidationError>,
133}
134
135impl ValidationResult {
136 pub fn new() -> Self {
138 Self { errors: Vec::new() }
139 }
140
141 pub fn is_valid(&self) -> bool {
143 self.errors.is_empty()
144 }
145
146 pub fn errors(&self) -> &[ValidationError] {
148 &self.errors
149 }
150
151 pub fn add_error(&mut self, error: ValidationError) {
153 self.errors.push(error);
154 }
155
156 pub fn merge(&mut self, other: ValidationResult) {
158 self.errors.extend(other.errors);
159 }
160
161 pub fn into_result(self) -> Result<(), ValidationErrors> {
164 if self.errors.is_empty() {
165 Ok(())
166 } else {
167 Err(ValidationErrors(self.errors))
168 }
169 }
170}
171
172pub trait Validator: Send + Sync {
177 fn validate(&self, value: &Value, field: &str) -> ValidationResult;
179
180 fn is_required(&self) -> bool;
182
183 fn is_nullable(&self) -> bool;
185
186 fn set_fail_fast(&mut self, _fail_fast: bool) {}
188}
189
190impl Validator for Box<dyn Validator> {
193 fn validate(&self, value: &Value, field: &str) -> ValidationResult {
194 (**self).validate(value, field)
195 }
196
197 fn is_required(&self) -> bool {
198 (**self).is_required()
199 }
200
201 fn is_nullable(&self) -> bool {
202 (**self).is_nullable()
203 }
204
205 fn set_fail_fast(&mut self, fail_fast: bool) {
206 (**self).set_fail_fast(fail_fast);
207 }
208}
209
210pub const MAX_PATTERN_INPUT_LENGTH: usize = 10_000;
218
219type CustomValidator = Box<dyn Fn(&Value) -> Option<String> + Send + Sync>;
222
223struct Base {
224 required: bool,
225 nullable: bool,
226 fail_fast: bool,
227 sensitive: bool,
230 custom_validators: Vec<CustomValidator>,
231}
232
233impl Base {
234 fn new() -> Self {
235 Self {
236 required: true,
237 nullable: false,
238 fail_fast: false,
239 sensitive: false,
240 custom_validators: Vec::new(),
241 }
242 }
243
244 fn is_required(&self) -> bool {
245 self.required
246 }
247
248 fn is_nullable(&self) -> bool {
249 self.nullable
250 }
251
252 fn display<'a>(&self, s: &'a str) -> &'a str {
254 if self.sensitive {
255 "***"
256 } else {
257 s
258 }
259 }
260
261 fn display_json(&self, value: &Value) -> String {
264 if self.sensitive {
265 "***".to_string()
266 } else {
267 serde_json::to_string(value).unwrap_or_else(|_| value.to_string())
268 }
269 }
270
271 fn err_value(&self, value: &Value) -> Option<Value> {
273 if self.sensitive {
274 None
275 } else {
276 Some(value.clone())
277 }
278 }
279
280 fn handle_null(&self, field: &str, fail_fast: bool) -> ValidationResult {
281 let mut result = ValidationResult::new();
282 if self.required && !self.nullable {
283 result.add_error(
284 ValidationError::new(field, "Field is required").with_code(codes::REQUIRED),
285 );
286 if fail_fast {
287 return result;
288 }
289 }
290 result
291 }
292
293 fn run_custom(
294 &self,
295 value: &Value,
296 field: &str,
297 result: &mut ValidationResult,
298 fail_fast: bool,
299 ) {
300 for validator in &self.custom_validators {
301 if let Some(message) = validator(value) {
302 result.add_error(
303 ValidationError::new(field, message)
304 .with_code(codes::CUSTOM)
305 .with_value(self.err_value(value)),
306 );
307 if fail_fast {
308 break;
309 }
310 }
311 }
312 }
313}
314
315macro_rules! base_methods {
316 ($type:ty) => {
317 impl $type {
318 pub fn optional(mut self) -> Self {
320 self.base.required = false;
321 self
322 }
323
324 pub fn nullable(mut self) -> Self {
326 self.base.nullable = true;
327 self
328 }
329
330 pub fn required(mut self) -> Self {
332 self.base.required = true;
333 self
334 }
335
336 pub fn sensitive(mut self, sensitive: bool) -> Self {
344 self.base.sensitive = sensitive;
345 self
346 }
347
348 pub fn custom<F>(mut self, f: F) -> Self
353 where
354 F: Fn(&Value) -> Option<String> + Send + Sync + 'static,
355 {
356 self.base.custom_validators.push(Box::new(f));
357 self
358 }
359
360 pub fn fail_fast(mut self, fail_fast: bool) -> Self {
365 self.set_fail_fast(fail_fast);
366 self
367 }
368 }
369 };
370}
371
372fn kind_name(value: &Value) -> &'static str {
377 match value {
378 Value::Null => "null",
379 Value::Bool(_) => "boolean",
380 Value::Number(n) => {
381 if n.is_i64() || n.is_u64() {
382 "integer"
383 } else if let Some(f) = n.as_f64() {
384 if f.fract() == 0.0 && f.is_finite() {
385 "integer"
386 } else {
387 "number"
388 }
389 } else {
390 "number"
391 }
392 }
393 Value::String(_) => "string",
394 Value::Array(_) => "array",
395 Value::Object(_) => "object",
396 }
397}
398
399static EMAIL_RE: OnceLock<Regex> = OnceLock::new();
401static URL_RE: OnceLock<Regex> = OnceLock::new();
402
403fn email_regex() -> &'static Regex {
404 EMAIL_RE
405 .get_or_init(|| Regex::new(r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$").unwrap())
406}
407
408fn url_regex() -> &'static Regex {
409 URL_RE.get_or_init(|| Regex::new(r"^https?://[^\s/$.?#].[^\s]*$").unwrap())
410}
411
412static UUID_RE: OnceLock<Regex> = OnceLock::new();
415static DATE_RE: OnceLock<Regex> = OnceLock::new();
416static DATETIME_RE: OnceLock<Regex> = OnceLock::new();
417static NUMERIC_RE: OnceLock<Regex> = OnceLock::new();
418
419fn uuid_regex() -> &'static Regex {
420 UUID_RE.get_or_init(|| {
421 Regex::new(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")
422 .unwrap()
423 })
424}
425
426fn date_regex() -> &'static Regex {
427 DATE_RE.get_or_init(|| Regex::new(r"^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$").unwrap())
428}
429
430fn datetime_regex() -> &'static Regex {
431 DATETIME_RE.get_or_init(|| {
432 Regex::new(
433 r"^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])T([01]\d|2[0-3]):[0-5]\d:[0-5]\d(\.\d+)?(Z|[+-]([01]\d|2[0-3]):[0-5]\d)$",
434 )
435 .unwrap()
436 })
437}
438
439fn numeric_regex() -> &'static Regex {
440 NUMERIC_RE.get_or_init(|| Regex::new(r"^-?(0|[1-9]\d*)(\.\d+)?([eE][+-]?\d+)?$").unwrap())
441}
442
443pub struct StringValidator {
445 base: Base,
446 min_length: Option<usize>,
447 max_length: Option<usize>,
448 pattern: Option<(String, Regex)>,
450 choices: Option<Vec<String>>,
451}
452
453fn anchor_pattern(source: &str) -> Result<Regex, regex::Error> {
455 Regex::new(&format!("^(?:{source})$"))
456}
457
458impl StringValidator {
459 pub fn new() -> Self {
461 Self {
462 base: Base::new(),
463 min_length: None,
464 max_length: None,
465 pattern: None,
466 choices: None,
467 }
468 }
469
470 pub fn min(mut self, min: usize) -> Self {
472 self.min_length = Some(min);
473 self
474 }
475
476 pub fn max(mut self, max: usize) -> Self {
478 self.max_length = Some(max);
479 self
480 }
481
482 pub fn pattern(mut self, pattern: Regex) -> Self {
487 let source = pattern.as_str().to_string();
488 let anchored = anchor_pattern(&source).unwrap_or(pattern);
489 self.pattern = Some((source, anchored));
490 self
491 }
492
493 pub fn try_pattern(mut self, pattern: &str) -> Result<Self, regex::Error> {
497 let anchored = anchor_pattern(pattern)?;
498 self.pattern = Some((pattern.to_string(), anchored));
499 Ok(self)
500 }
501
502 pub fn choices(mut self, choices: Vec<String>) -> Self {
504 self.choices = Some(choices);
505 self
506 }
507}
508
509base_methods!(StringValidator);
510
511impl Validator for StringValidator {
512 fn set_fail_fast(&mut self, fail_fast: bool) {
513 self.base.fail_fast = fail_fast;
514 }
515
516 fn validate(&self, value: &Value, field: &str) -> ValidationResult {
517 let fail_fast = self.base.fail_fast;
518 if value.is_null() {
519 return self.base.handle_null(field, fail_fast);
520 }
521
522 let mut result = ValidationResult::new();
523
524 let Some(s) = value.as_str() else {
525 result.add_error(
526 ValidationError::new(field, format!("Expected string, got {}", kind_name(value)))
527 .with_code(codes::TYPE)
528 .with_value(self.base.err_value(value)),
529 );
530 return result;
531 };
532
533 let len = s.chars().count();
534
535 if let Some(min) = self.min_length {
536 if len < min {
537 result.add_error(
538 ValidationError::new(
539 field,
540 format!("String length must be at least {min}, got {len}"),
541 )
542 .with_code(codes::MIN_LENGTH)
543 .with_value(self.base.err_value(value)),
544 );
545 if fail_fast {
546 return result;
547 }
548 }
549 }
550
551 if let Some(max) = self.max_length {
552 if len > max {
553 result.add_error(
554 ValidationError::new(
555 field,
556 format!("String length must be at most {max}, got {len}"),
557 )
558 .with_code(codes::MAX_LENGTH)
559 .with_value(self.base.err_value(value)),
560 );
561 if fail_fast {
562 return result;
563 }
564 }
565 }
566
567 if let Some((source, pattern)) = &self.pattern {
568 if len > MAX_PATTERN_INPUT_LENGTH || !pattern.is_match(s) {
571 result.add_error(
572 ValidationError::new(field, format!("String does not match pattern {source}"))
573 .with_code(codes::PATTERN)
574 .with_value(self.base.err_value(value)),
575 );
576 if fail_fast {
577 return result;
578 }
579 }
580 }
581
582 if let Some(choices) = &self.choices {
583 if !choices.iter().any(|c| c == s) {
584 result.add_error(
585 ValidationError::new(
586 field,
587 format!(
588 "Value must be one of {}, got '{}'",
589 choices.join(", "),
590 self.base.display(s)
591 ),
592 )
593 .with_code(codes::CHOICES)
594 .with_value(self.base.err_value(value)),
595 );
596 if fail_fast {
597 return result;
598 }
599 }
600 }
601
602 self.base.run_custom(value, field, &mut result, fail_fast);
603 result
604 }
605
606 fn is_required(&self) -> bool {
607 self.base.is_required()
608 }
609
610 fn is_nullable(&self) -> bool {
611 self.base.is_nullable()
612 }
613}
614
615pub struct IntValidator {
617 base: Base,
618 min_value: Option<i64>,
619 max_value: Option<i64>,
620}
621
622impl IntValidator {
623 pub fn new() -> Self {
625 Self {
626 base: Base::new(),
627 min_value: None,
628 max_value: None,
629 }
630 }
631
632 pub fn min(mut self, min: i64) -> Self {
634 self.min_value = Some(min);
635 self
636 }
637
638 pub fn max(mut self, max: i64) -> Self {
640 self.max_value = Some(max);
641 self
642 }
643}
644
645base_methods!(IntValidator);
646
647impl Validator for IntValidator {
648 fn set_fail_fast(&mut self, fail_fast: bool) {
649 self.base.fail_fast = fail_fast;
650 }
651
652 fn validate(&self, value: &Value, field: &str) -> ValidationResult {
653 let fail_fast = self.base.fail_fast;
654 if value.is_null() {
655 return self.base.handle_null(field, fail_fast);
656 }
657
658 let mut result = ValidationResult::new();
659
660 let parsed = value
661 .as_i64()
662 .or_else(|| value.as_u64().and_then(|u| i64::try_from(u).ok()))
663 .or_else(|| {
664 value.as_f64().and_then(|f| {
665 if f.fract() == 0.0
666 && f.is_finite()
667 && f >= i64::MIN as f64
668 && f <= i64::MAX as f64
669 {
670 Some(f as i64)
671 } else {
672 None
673 }
674 })
675 });
676
677 let Some(num) = parsed else {
678 result.add_error(
679 ValidationError::new(field, format!("Expected integer, got {}", kind_name(value)))
680 .with_code(codes::TYPE)
681 .with_value(self.base.err_value(value)),
682 );
683 return result;
684 };
685
686 if let Some(min) = self.min_value {
687 if num < min {
688 result.add_error(
689 ValidationError::new(field, format!("Value must be at least {min}, got {num}"))
690 .with_code(codes::MIN_VALUE)
691 .with_value(self.base.err_value(value)),
692 );
693 if fail_fast {
694 return result;
695 }
696 }
697 }
698
699 if let Some(max) = self.max_value {
700 if num > max {
701 result.add_error(
702 ValidationError::new(field, format!("Value must be at most {max}, got {num}"))
703 .with_code(codes::MAX_VALUE)
704 .with_value(self.base.err_value(value)),
705 );
706 if fail_fast {
707 return result;
708 }
709 }
710 }
711
712 self.base.run_custom(value, field, &mut result, fail_fast);
713 result
714 }
715
716 fn is_required(&self) -> bool {
717 self.base.is_required()
718 }
719
720 fn is_nullable(&self) -> bool {
721 self.base.is_nullable()
722 }
723}
724
725pub struct FloatValidator {
727 base: Base,
728 min_value: Option<f64>,
729 max_value: Option<f64>,
730}
731
732impl FloatValidator {
733 pub fn new() -> Self {
735 Self {
736 base: Base::new(),
737 min_value: None,
738 max_value: None,
739 }
740 }
741
742 pub fn min(mut self, min: f64) -> Self {
744 self.min_value = Some(min);
745 self
746 }
747
748 pub fn max(mut self, max: f64) -> Self {
750 self.max_value = Some(max);
751 self
752 }
753}
754
755base_methods!(FloatValidator);
756
757impl Validator for FloatValidator {
758 fn set_fail_fast(&mut self, fail_fast: bool) {
759 self.base.fail_fast = fail_fast;
760 }
761
762 fn validate(&self, value: &Value, field: &str) -> ValidationResult {
763 let fail_fast = self.base.fail_fast;
764 if value.is_null() {
765 return self.base.handle_null(field, fail_fast);
766 }
767
768 let mut result = ValidationResult::new();
769
770 let Some(num) = value.as_f64() else {
771 result.add_error(
772 ValidationError::new(field, format!("Expected number, got {}", kind_name(value)))
773 .with_code(codes::TYPE)
774 .with_value(self.base.err_value(value)),
775 );
776 return result;
777 };
778
779 if let Some(min) = self.min_value {
780 if num < min {
781 result.add_error(
782 ValidationError::new(field, format!("Value must be at least {min}, got {num}"))
783 .with_code(codes::MIN_VALUE)
784 .with_value(self.base.err_value(value)),
785 );
786 if fail_fast {
787 return result;
788 }
789 }
790 }
791
792 if let Some(max) = self.max_value {
793 if num > max {
794 result.add_error(
795 ValidationError::new(field, format!("Value must be at most {max}, got {num}"))
796 .with_code(codes::MAX_VALUE)
797 .with_value(self.base.err_value(value)),
798 );
799 if fail_fast {
800 return result;
801 }
802 }
803 }
804
805 self.base.run_custom(value, field, &mut result, fail_fast);
806 result
807 }
808
809 fn is_required(&self) -> bool {
810 self.base.is_required()
811 }
812
813 fn is_nullable(&self) -> bool {
814 self.base.is_nullable()
815 }
816}
817
818pub struct BoolValidator {
820 base: Base,
821}
822
823impl BoolValidator {
824 pub fn new() -> Self {
826 Self { base: Base::new() }
827 }
828}
829
830base_methods!(BoolValidator);
831
832impl Validator for BoolValidator {
833 fn set_fail_fast(&mut self, fail_fast: bool) {
834 self.base.fail_fast = fail_fast;
835 }
836
837 fn validate(&self, value: &Value, field: &str) -> ValidationResult {
838 let fail_fast = self.base.fail_fast;
839 if value.is_null() {
840 return self.base.handle_null(field, fail_fast);
841 }
842
843 let mut result = ValidationResult::new();
844
845 if !value.is_boolean() {
846 result.add_error(
847 ValidationError::new(field, format!("Expected boolean, got {}", kind_name(value)))
848 .with_code(codes::TYPE)
849 .with_value(self.base.err_value(value)),
850 );
851 return result;
852 }
853
854 self.base.run_custom(value, field, &mut result, fail_fast);
855 result
856 }
857
858 fn is_required(&self) -> bool {
859 self.base.is_required()
860 }
861
862 fn is_nullable(&self) -> bool {
863 self.base.is_nullable()
864 }
865}
866
867pub struct EmailValidator {
869 base: Base,
870}
871
872impl EmailValidator {
873 pub fn new() -> Self {
875 Self { base: Base::new() }
876 }
877}
878
879base_methods!(EmailValidator);
880
881impl Validator for EmailValidator {
882 fn set_fail_fast(&mut self, fail_fast: bool) {
883 self.base.fail_fast = fail_fast;
884 }
885
886 fn validate(&self, value: &Value, field: &str) -> ValidationResult {
887 let fail_fast = self.base.fail_fast;
888 if value.is_null() {
889 return self.base.handle_null(field, fail_fast);
890 }
891
892 let mut result = ValidationResult::new();
893
894 let Some(s) = value.as_str() else {
895 result.add_error(
896 ValidationError::new(field, format!("Expected string, got {}", kind_name(value)))
897 .with_code(codes::TYPE)
898 .with_value(self.base.err_value(value)),
899 );
900 return result;
901 };
902
903 if s.chars().count() > MAX_PATTERN_INPUT_LENGTH || !email_regex().is_match(s) {
905 result.add_error(
906 ValidationError::new(
907 field,
908 format!("Invalid email address: {}", self.base.display(s)),
909 )
910 .with_code(codes::EMAIL)
911 .with_value(self.base.err_value(value)),
912 );
913 if fail_fast {
914 return result;
915 }
916 }
917
918 self.base.run_custom(value, field, &mut result, fail_fast);
919 result
920 }
921
922 fn is_required(&self) -> bool {
923 self.base.is_required()
924 }
925
926 fn is_nullable(&self) -> bool {
927 self.base.is_nullable()
928 }
929}
930
931pub struct UrlValidator {
933 base: Base,
934}
935
936impl UrlValidator {
937 pub fn new() -> Self {
939 Self { base: Base::new() }
940 }
941}
942
943base_methods!(UrlValidator);
944
945impl Validator for UrlValidator {
946 fn set_fail_fast(&mut self, fail_fast: bool) {
947 self.base.fail_fast = fail_fast;
948 }
949
950 fn validate(&self, value: &Value, field: &str) -> ValidationResult {
951 let fail_fast = self.base.fail_fast;
952 if value.is_null() {
953 return self.base.handle_null(field, fail_fast);
954 }
955
956 let mut result = ValidationResult::new();
957
958 let Some(s) = value.as_str() else {
959 result.add_error(
960 ValidationError::new(field, format!("Expected string, got {}", kind_name(value)))
961 .with_code(codes::TYPE)
962 .with_value(self.base.err_value(value)),
963 );
964 return result;
965 };
966
967 if s.chars().count() > MAX_PATTERN_INPUT_LENGTH || !url_regex().is_match(s) {
969 result.add_error(
970 ValidationError::new(field, format!("Invalid URL: {}", self.base.display(s)))
971 .with_code(codes::URL)
972 .with_value(self.base.err_value(value)),
973 );
974 if fail_fast {
975 return result;
976 }
977 }
978
979 self.base.run_custom(value, field, &mut result, fail_fast);
980 result
981 }
982
983 fn is_required(&self) -> bool {
984 self.base.is_required()
985 }
986
987 fn is_nullable(&self) -> bool {
988 self.base.is_nullable()
989 }
990}
991
992macro_rules! fixed_pattern_validator {
995 ($type:ident, $doc:literal, $regex_fn:ident, $code:expr, $msg:literal) => {
996 #[doc = $doc]
997 pub struct $type {
998 base: Base,
999 }
1000
1001 impl $type {
1002 pub fn new() -> Self {
1004 Self { base: Base::new() }
1005 }
1006 }
1007
1008 base_methods!($type);
1009
1010 impl Default for $type {
1011 fn default() -> Self {
1012 Self::new()
1013 }
1014 }
1015
1016 impl Validator for $type {
1017 fn set_fail_fast(&mut self, fail_fast: bool) {
1018 self.base.fail_fast = fail_fast;
1019 }
1020
1021 fn validate(&self, value: &Value, field: &str) -> ValidationResult {
1022 let fail_fast = self.base.fail_fast;
1023 if value.is_null() {
1024 return self.base.handle_null(field, fail_fast);
1025 }
1026
1027 let mut result = ValidationResult::new();
1028
1029 let Some(s) = value.as_str() else {
1030 result.add_error(
1031 ValidationError::new(
1032 field,
1033 format!("Expected string, got {}", kind_name(value)),
1034 )
1035 .with_code(codes::TYPE)
1036 .with_value(self.base.err_value(value)),
1037 );
1038 return result;
1039 };
1040
1041 if s.chars().count() > MAX_PATTERN_INPUT_LENGTH || !$regex_fn().is_match(s) {
1043 result.add_error(
1044 ValidationError::new(field, format!($msg, self.base.display(s)))
1045 .with_code($code)
1046 .with_value(self.base.err_value(value)),
1047 );
1048 if fail_fast {
1049 return result;
1050 }
1051 }
1052
1053 self.base.run_custom(value, field, &mut result, fail_fast);
1054 result
1055 }
1056
1057 fn is_required(&self) -> bool {
1058 self.base.is_required()
1059 }
1060
1061 fn is_nullable(&self) -> bool {
1062 self.base.is_nullable()
1063 }
1064 }
1065 };
1066}
1067
1068fixed_pattern_validator!(
1069 UuidValidator,
1070 "Validator for UUID strings.",
1071 uuid_regex,
1072 codes::UUID,
1073 "Invalid UUID: {}"
1074);
1075
1076fixed_pattern_validator!(
1077 DateValidator,
1078 "Validator for `YYYY-MM-DD` date strings.",
1079 date_regex,
1080 codes::DATE,
1081 "Invalid date: {}"
1082);
1083
1084fixed_pattern_validator!(
1085 DatetimeValidator,
1086 "Validator for ISO-8601 style datetime strings.",
1087 datetime_regex,
1088 codes::DATETIME,
1089 "Invalid datetime: {}"
1090);
1091
1092fixed_pattern_validator!(
1093 NumericValidator,
1094 "Validator for strings that contain a valid JSON-style number.",
1095 numeric_regex,
1096 codes::NUMERIC,
1097 "Expected numeric string, got {}"
1098);
1099
1100pub struct NotEmptyValidator {
1102 base: Base,
1103}
1104
1105impl NotEmptyValidator {
1106 pub fn new() -> Self {
1108 Self { base: Base::new() }
1109 }
1110}
1111
1112base_methods!(NotEmptyValidator);
1113
1114impl Validator for NotEmptyValidator {
1115 fn set_fail_fast(&mut self, fail_fast: bool) {
1116 self.base.fail_fast = fail_fast;
1117 }
1118
1119 fn validate(&self, value: &Value, field: &str) -> ValidationResult {
1120 let fail_fast = self.base.fail_fast;
1121 if value.is_null() {
1122 return self.base.handle_null(field, fail_fast);
1123 }
1124
1125 let mut result = ValidationResult::new();
1126
1127 let is_empty = match value {
1128 Value::String(s) => s.is_empty(),
1129 Value::Array(arr) => arr.is_empty(),
1130 Value::Object(map) => map.is_empty(),
1131 _ => {
1132 result.add_error(
1133 ValidationError::new(
1134 field,
1135 format!(
1136 "Expected string, array, or object, got {}",
1137 kind_name(value)
1138 ),
1139 )
1140 .with_code(codes::TYPE)
1141 .with_value(self.base.err_value(value)),
1142 );
1143 return result;
1144 }
1145 };
1146
1147 if is_empty {
1148 result.add_error(
1149 ValidationError::new(field, "Value must not be empty")
1150 .with_code(codes::NOT_EMPTY)
1151 .with_value(self.base.err_value(value)),
1152 );
1153 if fail_fast {
1154 return result;
1155 }
1156 }
1157
1158 self.base.run_custom(value, field, &mut result, fail_fast);
1159 result
1160 }
1161
1162 fn is_required(&self) -> bool {
1163 self.base.is_required()
1164 }
1165
1166 fn is_nullable(&self) -> bool {
1167 self.base.is_nullable()
1168 }
1169}
1170
1171pub struct EnumValidator {
1174 base: Base,
1175 values: Vec<Value>,
1176}
1177
1178impl EnumValidator {
1179 pub fn new(values: Vec<Value>) -> Self {
1181 Self {
1182 base: Base::new(),
1183 values,
1184 }
1185 }
1186}
1187
1188base_methods!(EnumValidator);
1189
1190impl Validator for EnumValidator {
1191 fn set_fail_fast(&mut self, fail_fast: bool) {
1192 self.base.fail_fast = fail_fast;
1193 }
1194
1195 fn validate(&self, value: &Value, field: &str) -> ValidationResult {
1196 let fail_fast = self.base.fail_fast;
1197 if value.is_null() {
1198 return self.base.handle_null(field, fail_fast);
1199 }
1200
1201 let mut result = ValidationResult::new();
1202
1203 if !self.values.iter().any(|v| v == value) {
1204 let allowed = self
1205 .values
1206 .iter()
1207 .map(|v| serde_json::to_string(v).unwrap_or_else(|_| v.to_string()))
1208 .collect::<Vec<_>>()
1209 .join(", ");
1210 let got = self.base.display_json(value);
1211 result.add_error(
1212 ValidationError::new(field, format!("Value must be one of {allowed}, got {got}"))
1213 .with_code(codes::ENUM)
1214 .with_value(self.base.err_value(value)),
1215 );
1216 if fail_fast {
1217 return result;
1218 }
1219 }
1220
1221 self.base.run_custom(value, field, &mut result, fail_fast);
1222 result
1223 }
1224
1225 fn is_required(&self) -> bool {
1226 self.base.is_required()
1227 }
1228
1229 fn is_nullable(&self) -> bool {
1230 self.base.is_nullable()
1231 }
1232}
1233
1234pub struct OneOfValidator {
1237 base: Base,
1238 branches: Vec<Box<dyn Validator>>,
1239}
1240
1241impl OneOfValidator {
1242 pub fn new(branches: Vec<Box<dyn Validator>>) -> Self {
1244 Self {
1245 base: Base::new(),
1246 branches,
1247 }
1248 }
1249}
1250
1251base_methods!(OneOfValidator);
1252
1253impl Validator for OneOfValidator {
1254 fn set_fail_fast(&mut self, fail_fast: bool) {
1255 self.base.fail_fast = fail_fast;
1256 for branch in &mut self.branches {
1257 branch.set_fail_fast(fail_fast);
1258 }
1259 }
1260
1261 fn validate(&self, value: &Value, field: &str) -> ValidationResult {
1262 let fail_fast = self.base.fail_fast;
1263 if value.is_null() {
1264 return self.base.handle_null(field, fail_fast);
1265 }
1266
1267 let mut result = ValidationResult::new();
1268
1269 let any_match = self
1270 .branches
1271 .iter()
1272 .any(|branch| branch.validate(value, field).is_valid());
1273
1274 if !any_match {
1275 result.add_error(
1276 ValidationError::new(field, "Value does not match any allowed schema")
1277 .with_code(codes::ONE_OF)
1278 .with_value(self.base.err_value(value)),
1279 );
1280 if fail_fast {
1281 return result;
1282 }
1283 }
1284
1285 self.base.run_custom(value, field, &mut result, fail_fast);
1286 result
1287 }
1288
1289 fn is_required(&self) -> bool {
1290 self.base.is_required()
1291 }
1292
1293 fn is_nullable(&self) -> bool {
1294 self.base.is_nullable()
1295 }
1296}
1297
1298pub struct VecValidator {
1300 base: Base,
1301 item_validator: Option<Box<dyn Validator>>,
1302 min_length: Option<usize>,
1303 max_length: Option<usize>,
1304}
1305
1306impl VecValidator {
1307 pub fn new() -> Self {
1309 Self {
1310 base: Base::new(),
1311 item_validator: None,
1312 min_length: None,
1313 max_length: None,
1314 }
1315 }
1316
1317 pub fn item(mut self, mut validator: impl Validator + 'static) -> Self {
1319 validator.set_fail_fast(self.base.fail_fast);
1320 self.item_validator = Some(Box::new(validator));
1321 self
1322 }
1323
1324 pub fn min(mut self, min: usize) -> Self {
1326 self.min_length = Some(min);
1327 self
1328 }
1329
1330 pub fn max(mut self, max: usize) -> Self {
1332 self.max_length = Some(max);
1333 self
1334 }
1335}
1336
1337base_methods!(VecValidator);
1338
1339impl Validator for VecValidator {
1340 fn set_fail_fast(&mut self, fail_fast: bool) {
1341 self.base.fail_fast = fail_fast;
1342 if let Some(item_validator) = self.item_validator.as_mut() {
1343 item_validator.set_fail_fast(fail_fast);
1344 }
1345 }
1346
1347 fn validate(&self, value: &Value, field: &str) -> ValidationResult {
1348 let fail_fast = self.base.fail_fast;
1349 if value.is_null() {
1350 return self.base.handle_null(field, fail_fast);
1351 }
1352
1353 let mut result = ValidationResult::new();
1354
1355 let Some(arr) = value.as_array() else {
1356 result.add_error(
1357 ValidationError::new(field, format!("Expected array, got {}", kind_name(value)))
1358 .with_code(codes::TYPE)
1359 .with_value(self.base.err_value(value)),
1360 );
1361 return result;
1362 };
1363
1364 if let Some(min) = self.min_length {
1365 if arr.len() < min {
1366 result.add_error(
1367 ValidationError::new(
1368 field,
1369 format!("Array length must be at least {min}, got {}", arr.len()),
1370 )
1371 .with_code(codes::MIN_LENGTH)
1372 .with_value(self.base.err_value(value)),
1373 );
1374 if fail_fast {
1375 return result;
1376 }
1377 }
1378 }
1379
1380 if let Some(max) = self.max_length {
1381 if arr.len() > max {
1382 result.add_error(
1383 ValidationError::new(
1384 field,
1385 format!("Array length must be at most {max}, got {}", arr.len()),
1386 )
1387 .with_code(codes::MAX_LENGTH)
1388 .with_value(self.base.err_value(value)),
1389 );
1390 if fail_fast {
1391 return result;
1392 }
1393 }
1394 }
1395
1396 if let Some(item_validator) = &self.item_validator {
1397 for (i, item) in arr.iter().enumerate() {
1398 let path = format!("{field}[{i}]");
1399 result.merge(item_validator.validate(item, &path));
1400 if fail_fast && !result.is_valid() {
1401 return result;
1402 }
1403 }
1404 }
1405
1406 self.base.run_custom(value, field, &mut result, fail_fast);
1407 result
1408 }
1409
1410 fn is_required(&self) -> bool {
1411 self.base.is_required()
1412 }
1413
1414 fn is_nullable(&self) -> bool {
1415 self.base.is_nullable()
1416 }
1417}
1418
1419pub struct MapValidator {
1421 base: Base,
1422 schema: HashMap<String, Box<dyn Validator>>,
1423 strict: bool,
1424}
1425
1426impl MapValidator {
1427 pub fn new() -> Self {
1429 Self {
1430 base: Base::new(),
1431 schema: HashMap::new(),
1432 strict: false,
1433 }
1434 }
1435
1436 pub fn field(
1438 mut self,
1439 name: impl Into<String>,
1440 mut validator: impl Validator + 'static,
1441 ) -> Self {
1442 validator.set_fail_fast(self.base.fail_fast);
1443 self.schema.insert(name.into(), Box::new(validator));
1444 self
1445 }
1446
1447 pub fn schema(mut self, mut schema: HashMap<String, Box<dyn Validator>>) -> Self {
1449 let fail_fast = self.base.fail_fast;
1450 for v in schema.values_mut() {
1451 v.set_fail_fast(fail_fast);
1452 }
1453 self.schema = schema;
1454 self
1455 }
1456
1457 pub fn strict(mut self, strict: bool) -> Self {
1461 self.strict = strict;
1462 self
1463 }
1464}
1465
1466base_methods!(MapValidator);
1467
1468impl Default for MapValidator {
1469 fn default() -> Self {
1470 Self::new()
1471 }
1472}
1473
1474impl Validator for MapValidator {
1475 fn set_fail_fast(&mut self, fail_fast: bool) {
1476 self.base.fail_fast = fail_fast;
1477 for v in self.schema.values_mut() {
1478 v.set_fail_fast(fail_fast);
1479 }
1480 }
1481
1482 fn validate(&self, value: &Value, field: &str) -> ValidationResult {
1483 let fail_fast = self.base.fail_fast;
1484 if value.is_null() {
1485 return self.base.handle_null(field, fail_fast);
1486 }
1487
1488 let mut result = ValidationResult::new();
1489
1490 let Some(map) = value.as_object() else {
1491 result.add_error(
1492 ValidationError::new(field, format!("Expected object, got {}", kind_name(value)))
1493 .with_code(codes::TYPE)
1494 .with_value(self.base.err_value(value)),
1495 );
1496 return result;
1497 };
1498
1499 if self.strict {
1500 for (key, val) in map.iter() {
1501 if !self.schema.contains_key(key) {
1502 result.add_error(
1503 ValidationError::new(format!("{field}.{key}"), "Unknown field")
1504 .with_code(codes::UNKNOWN_FIELD)
1505 .with_value(self.base.err_value(val)),
1506 );
1507 if fail_fast {
1508 return result;
1509 }
1510 }
1511 }
1512 }
1513
1514 for (key, validator) in &self.schema {
1515 let path = format!("{field}.{key}");
1516 if let Some(v) = map.get(key) {
1517 result.merge(validator.validate(v, &path));
1518 } else if validator.is_required() {
1519 result.add_error(
1520 ValidationError::new(&path, "Field is required").with_code(codes::REQUIRED),
1521 );
1522 }
1523 if fail_fast && !result.is_valid() {
1524 return result;
1525 }
1526 }
1527
1528 self.base.run_custom(value, field, &mut result, fail_fast);
1529 result
1530 }
1531
1532 fn is_required(&self) -> bool {
1533 self.base.is_required()
1534 }
1535
1536 fn is_nullable(&self) -> bool {
1537 self.base.is_nullable()
1538 }
1539}
1540
1541#[derive(Default)]
1543pub struct Schema {
1544 fields: HashMap<String, Box<dyn Validator>>,
1545 strict: bool,
1546 fail_fast: bool,
1547}
1548
1549impl Schema {
1550 pub fn new() -> Self {
1552 Self {
1553 fields: HashMap::new(),
1554 strict: false,
1555 fail_fast: false,
1556 }
1557 }
1558
1559 pub fn field(
1561 mut self,
1562 name: impl Into<String>,
1563 mut validator: impl Validator + 'static,
1564 ) -> Self {
1565 validator.set_fail_fast(self.fail_fast);
1566 self.fields.insert(name.into(), Box::new(validator));
1567 self
1568 }
1569
1570 pub fn strict(mut self, strict: bool) -> Self {
1575 self.strict = strict;
1576 self
1577 }
1578
1579 pub fn fail_fast(mut self, fail_fast: bool) -> Self {
1584 self.fail_fast = fail_fast;
1585 for v in self.fields.values_mut() {
1586 v.set_fail_fast(fail_fast);
1587 }
1588 self
1589 }
1590
1591 pub fn validate(&self, data: &Value) -> ValidationResult {
1593 let mut result = ValidationResult::new();
1594 let fail_fast = self.fail_fast;
1595
1596 let Some(map) = data.as_object() else {
1597 result.add_error(
1598 ValidationError::new("root", format!("Expected object, got {}", kind_name(data)))
1599 .with_code(codes::TYPE)
1600 .with_value(data.clone()),
1601 );
1602 return result;
1603 };
1604
1605 if self.strict {
1606 for (key, val) in map.iter() {
1607 if !self.fields.contains_key(key) {
1608 result.add_error(
1609 ValidationError::new(key, "Unknown field")
1610 .with_code(codes::UNKNOWN_FIELD)
1611 .with_value(val.clone()),
1612 );
1613 if fail_fast {
1614 return result;
1615 }
1616 }
1617 }
1618 }
1619
1620 for (field, validator) in &self.fields {
1621 if let Some(value) = map.get(field) {
1622 result.merge(validator.validate(value, field));
1623 } else if validator.is_required() {
1624 result.add_error(
1625 ValidationError::new(field, "Field is required").with_code(codes::REQUIRED),
1626 );
1627 }
1628 if fail_fast && !result.is_valid() {
1629 return result;
1630 }
1631 }
1632
1633 result
1634 }
1635
1636 pub fn validate_or_raise(&self, data: &Value) -> Result<(), ValidationResult> {
1638 let result = self.validate(data);
1639 if result.is_valid() {
1640 Ok(())
1641 } else {
1642 Err(result)
1643 }
1644 }
1645
1646 pub fn try_validate(&self, data: &Value) -> Result<(), ValidationErrors> {
1649 self.validate(data).into_result()
1650 }
1651}
1652
1653pub mod validators {
1655 use super::*;
1656
1657 pub fn string() -> StringValidator {
1659 StringValidator::new()
1660 }
1661
1662 pub fn int() -> IntValidator {
1664 IntValidator::new()
1665 }
1666
1667 pub fn float() -> FloatValidator {
1669 FloatValidator::new()
1670 }
1671
1672 pub fn bool() -> BoolValidator {
1674 BoolValidator::new()
1675 }
1676
1677 pub fn email() -> EmailValidator {
1679 EmailValidator::new()
1680 }
1681
1682 pub fn url() -> UrlValidator {
1684 UrlValidator::new()
1685 }
1686
1687 pub fn vec() -> VecValidator {
1689 VecValidator::new()
1690 }
1691
1692 pub fn list() -> VecValidator {
1694 VecValidator::new()
1695 }
1696
1697 pub fn map() -> MapValidator {
1699 MapValidator::new()
1700 }
1701
1702 pub fn dict() -> MapValidator {
1704 MapValidator::new()
1705 }
1706
1707 pub fn uuid() -> UuidValidator {
1709 UuidValidator::new()
1710 }
1711
1712 pub fn date() -> DateValidator {
1714 DateValidator::new()
1715 }
1716
1717 pub fn datetime() -> DatetimeValidator {
1719 DatetimeValidator::new()
1720 }
1721
1722 pub fn numeric() -> NumericValidator {
1724 NumericValidator::new()
1725 }
1726
1727 pub fn not_empty() -> NotEmptyValidator {
1729 NotEmptyValidator::new()
1730 }
1731
1732 pub fn enum_values(values: Vec<Value>) -> EnumValidator {
1737 EnumValidator::new(values)
1738 }
1739
1740 #[allow(non_snake_case)]
1742 pub fn r#enum(values: Vec<Value>) -> EnumValidator {
1743 EnumValidator::new(values)
1744 }
1745
1746 pub fn one_of(branches: Vec<Box<dyn Validator>>) -> OneOfValidator {
1749 OneOfValidator::new(branches)
1750 }
1751
1752 pub fn regex(re: Regex) -> StringValidator {
1754 StringValidator::new().pattern(re)
1755 }
1756}
1757
1758macro_rules! impl_default {
1760 ($($t:ty),* $(,)?) => {
1761 $(impl Default for $t {
1762 fn default() -> Self {
1763 Self::new()
1764 }
1765 })*
1766 };
1767}
1768
1769impl_default!(
1770 StringValidator,
1771 IntValidator,
1772 FloatValidator,
1773 BoolValidator,
1774 EmailValidator,
1775 UrlValidator,
1776 NotEmptyValidator,
1777 VecValidator,
1778);
1779
1780#[cfg(test)]
1781mod tests {
1782 use super::*;
1783 use regex::Regex;
1784 use serde_json::json;
1785
1786 #[test]
1787 fn test_string_validator() {
1788 let validator = validators::string().min(3).max(10);
1789 assert!(validator.validate(&json!("hello"), "name").is_valid());
1790 assert!(!validator.validate(&json!("ab"), "name").is_valid());
1791 assert!(!validator.validate(&json!("hello world"), "name").is_valid());
1792
1793 let pattern_validator = validators::string().try_pattern(r"^\d{3}-\d{4}$").unwrap();
1794 assert!(pattern_validator
1795 .validate(&json!("123-4567"), "phone")
1796 .is_valid());
1797 assert!(!pattern_validator
1798 .validate(&json!("12-3456"), "phone")
1799 .is_valid());
1800
1801 let choices_validator =
1802 validators::string().choices(vec!["light".to_string(), "dark".to_string()]);
1803 assert!(choices_validator
1804 .validate(&json!("light"), "theme")
1805 .is_valid());
1806 assert!(!choices_validator
1807 .validate(&json!("red"), "theme")
1808 .is_valid());
1809
1810 let result = validators::string().validate(&json!(42), "name");
1811 assert!(!result.is_valid());
1812 assert!(result.errors()[0]
1813 .message
1814 .contains("Expected string, got integer"));
1815 assert_eq!(result.errors()[0].code, codes::TYPE);
1816 }
1817
1818 #[test]
1819 fn test_int_validator() {
1820 let validator = validators::int().min(0).max(120);
1821 assert!(validator.validate(&json!(25), "age").is_valid());
1822 assert!(!validator.validate(&json!(-1), "age").is_valid());
1823 assert!(!validator.validate(&json!(150), "age").is_valid());
1824
1825 let result = validator.validate(&json!(1.5), "age");
1826 assert!(!result.is_valid());
1827 assert!(result.errors()[0]
1828 .message
1829 .contains("Expected integer, got number"));
1830 assert_eq!(result.errors()[0].code, codes::TYPE);
1831
1832 let result = validator.validate(&json!("25"), "age");
1833 assert!(!result.is_valid());
1834 assert!(result.errors()[0]
1835 .message
1836 .contains("Expected integer, got string"));
1837 }
1838
1839 #[test]
1840 fn test_float_validator() {
1841 let validator = validators::float().min(0.0).max(100.0);
1842 assert!(validator.validate(&json!(25.5), "score").is_valid());
1843 assert!(validator.validate(&json!(25), "score").is_valid());
1844 assert!(!validator.validate(&json!(150.0), "score").is_valid());
1845
1846 let result = validator.validate(&json!("25"), "score");
1847 assert!(!result.is_valid());
1848 assert!(result.errors()[0]
1849 .message
1850 .contains("Expected number, got string"));
1851 }
1852
1853 #[test]
1854 fn test_bool_validator() {
1855 let validator = validators::bool();
1856 assert!(validator.validate(&json!(true), "active").is_valid());
1857
1858 let result = validator.validate(&json!("true"), "active");
1859 assert!(!result.is_valid());
1860 assert!(result.errors()[0]
1861 .message
1862 .contains("Expected boolean, got string"));
1863 }
1864
1865 #[test]
1866 fn test_email_validator() {
1867 let validator = validators::email();
1868 assert!(validator
1869 .validate(&json!("user@example.com"), "email")
1870 .is_valid());
1871
1872 let result = validator.validate(&json!("invalid-email"), "email");
1873 assert!(!result.is_valid());
1874 assert!(result.errors()[0].message.contains("Invalid email address"));
1875 assert_eq!(result.errors()[0].code, codes::EMAIL);
1876
1877 let result = validator.validate(&json!(123), "email");
1878 assert!(!result.is_valid());
1879 assert!(result.errors()[0].message.contains("Expected string"));
1880 assert_eq!(result.errors()[0].code, codes::TYPE);
1881 }
1882
1883 #[test]
1884 fn test_url_validator() {
1885 let validator = validators::url();
1886 assert!(validator
1887 .validate(&json!("https://example.com"), "url")
1888 .is_valid());
1889
1890 let result = validator.validate(&json!("not-a-url"), "url");
1891 assert!(!result.is_valid());
1892 assert!(result.errors()[0].message.contains("Invalid URL"));
1893 assert_eq!(result.errors()[0].code, codes::URL);
1894 }
1895
1896 #[test]
1897 fn test_vec_validator() {
1898 let validator = validators::vec()
1899 .item(validators::int().min(0))
1900 .min(1)
1901 .max(3);
1902
1903 assert!(validator.validate(&json!([1, 2]), "items").is_valid());
1904 assert!(!validator.validate(&json!([]), "items").is_valid());
1905 assert!(!validator.validate(&json!([1, 2, 3, 4]), "items").is_valid());
1906
1907 let result = validator.validate(&json!(["bad"]), "items");
1908 assert!(!result.is_valid());
1909 assert_eq!(result.errors()[0].field, "items[0]");
1910 assert!(result.errors()[0].message.contains("Expected integer"));
1911 }
1912
1913 #[test]
1914 fn test_map_validator() {
1915 let validator = validators::map()
1916 .field("name", validators::string().min(1))
1917 .field("age", validators::int());
1918
1919 assert!(validator
1920 .validate(&json!({"name": "Ada", "age": 30}), "user")
1921 .is_valid());
1922
1923 let result = validator.validate(&json!({"name": "Ada"}), "user");
1924 assert!(!result.is_valid());
1925 assert_eq!(result.errors()[0].field, "user.age");
1926 assert_eq!(result.errors()[0].message, "Field is required");
1927 assert_eq!(result.errors()[0].code, codes::REQUIRED);
1928 }
1929
1930 #[test]
1931 fn test_optional_nullable() {
1932 let schema = Schema::new()
1933 .field("name", validators::string())
1934 .field("bio", validators::string().optional().nullable());
1935
1936 assert!(schema.validate(&json!({"name": "Ada"})).is_valid());
1937 assert!(schema
1938 .validate(&json!({"name": "Ada", "bio": null}))
1939 .is_valid());
1940
1941 let result = schema.validate(&json!({"name": "Ada", "bio": 123}));
1942 assert!(!result.is_valid());
1943 assert!(result.errors()[0].message.contains("Expected string"));
1944
1945 let required = validators::string();
1946 assert!(!required.validate(&Value::Null, "name").is_valid());
1947
1948 let nullable = validators::string().nullable();
1949 assert!(nullable.validate(&Value::Null, "name").is_valid());
1950 }
1951
1952 #[test]
1953 fn test_custom_validator() {
1954 let validator = validators::int().custom(|value| {
1955 if let Some(n) = value.as_i64() {
1956 if n % 2 == 0 {
1957 return None;
1958 }
1959 }
1960 Some("value must be even".to_string())
1961 });
1962
1963 assert!(validator.validate(&json!(4), "x").is_valid());
1964
1965 let result = validator.validate(&json!(3), "x");
1966 assert!(!result.is_valid());
1967 assert_eq!(result.errors()[0].code, codes::CUSTOM);
1968 }
1969
1970 #[test]
1971 fn test_strict_schema() {
1972 let schema = Schema::new()
1973 .field("name", validators::string())
1974 .strict(true);
1975
1976 let result = schema.validate(&json!({"name": "Ada", "extra": 1}));
1977 assert!(!result.is_valid());
1978 assert_eq!(result.errors()[0].field, "extra");
1979 assert_eq!(result.errors()[0].message, "Unknown field");
1980 assert_eq!(result.errors()[0].code, codes::UNKNOWN_FIELD);
1981
1982 assert!(schema.validate(&json!({"name": "Ada"})).is_valid());
1983 }
1984
1985 #[test]
1986 fn test_strict_map() {
1987 let validator = validators::map()
1988 .field("name", validators::string())
1989 .strict(true);
1990
1991 let result = validator.validate(&json!({"name": "Ada", "extra": 1}), "user");
1992 assert!(!result.is_valid());
1993 assert_eq!(result.errors()[0].field, "user.extra");
1994 assert_eq!(result.errors()[0].message, "Unknown field");
1995 }
1996
1997 #[test]
1998 fn test_missing_required() {
1999 let schema = Schema::new()
2000 .field("name", validators::string())
2001 .field("age", validators::int());
2002
2003 let result = schema.validate(&json!({"name": "Ada"}));
2004 assert!(!result.is_valid());
2005 assert!(result
2006 .errors()
2007 .iter()
2008 .any(|e| e.field == "age" && e.message == "Field is required"));
2009 }
2010
2011 #[test]
2012 fn test_nested_map_vec_paths() {
2013 let schema = Schema::new().field(
2014 "user",
2015 validators::map().field("tags", validators::vec().item(validators::string().min(2))),
2016 );
2017
2018 let result = schema.validate(&json!({"user": {"tags": ["a"]}}));
2019 assert!(!result.is_valid());
2020 assert_eq!(result.errors()[0].field, "user.tags[0]");
2021 }
2022
2023 #[test]
2024 fn test_pattern_infallible() {
2025 let validator = validators::string().pattern(Regex::new(r"^[a-z]+$").unwrap());
2026 assert!(validator.validate(&json!("abc"), "code").is_valid());
2027 assert!(!validator.validate(&json!("ABC"), "code").is_valid());
2028 }
2029
2030 #[test]
2031 fn test_validate_or_raise() {
2032 let schema = Schema::new().field("name", validators::string());
2033 assert!(schema.validate_or_raise(&json!({"name": "Ada"})).is_ok());
2034 assert!(schema.validate_or_raise(&json!({})).is_err());
2035 }
2036
2037 #[test]
2038 fn test_fail_fast_schema() {
2039 let schema = Schema::new()
2040 .fail_fast(true)
2041 .field("a", validators::string().min(2))
2042 .field("b", validators::int().min(0));
2043
2044 let result = schema.validate(&json!({"a": "x", "b": -1}));
2045 assert!(!result.is_valid());
2046 assert_eq!(result.errors().len(), 1);
2047
2048 let schema_default = Schema::new()
2049 .field("a", validators::string().min(2))
2050 .field("b", validators::int().min(0));
2051 let result_default = schema_default.validate(&json!({"a": "x", "b": -1}));
2052 assert_eq!(result_default.errors().len(), 2);
2053 }
2054
2055 #[test]
2056 fn test_fail_fast_map() {
2057 let validator = validators::map()
2058 .fail_fast(true)
2059 .field("name", validators::string().min(2))
2060 .field("age", validators::int().min(0));
2061
2062 let result = validator.validate(&json!({"name": "x", "age": -1}), "user");
2063 assert!(!result.is_valid());
2064 assert_eq!(result.errors().len(), 1);
2065
2066 let validator_default = validators::map()
2067 .field("name", validators::string().min(2))
2068 .field("age", validators::int().min(0));
2069 let result_default = validator_default.validate(&json!({"name": "x", "age": -1}), "user");
2070 assert_eq!(result_default.errors().len(), 2);
2071 }
2072
2073 #[test]
2074 fn test_fail_fast_vec() {
2075 let validator = validators::vec()
2076 .fail_fast(true)
2077 .item(validators::int().min(0));
2078
2079 let result = validator.validate(&json!([-1, -2]), "items");
2080 assert!(!result.is_valid());
2081 assert_eq!(result.errors().len(), 1);
2082 assert_eq!(result.errors()[0].field, "items[0]");
2083
2084 let result_default = validators::vec()
2085 .item(validators::int().min(0))
2086 .validate(&json!([-1, -2]), "items");
2087 assert_eq!(result_default.errors().len(), 2);
2088 }
2089
2090 #[test]
2091 fn test_fail_fast_nested() {
2092 let schema = Schema::new().fail_fast(true).field(
2093 "user",
2094 validators::map().field("tags", validators::vec().item(validators::int().min(0))),
2095 );
2096
2097 let result = schema.validate(&json!({"user": {"tags": [-1, -2]}}));
2098 assert!(!result.is_valid());
2099 assert_eq!(result.errors().len(), 1);
2100 assert_eq!(result.errors()[0].field, "user.tags[0]");
2101 }
2102
2103 #[test]
2104 fn test_fail_fast_leaf_stops_at_first_constraint() {
2105 let validator = validators::string()
2106 .min(5)
2107 .try_pattern(r"^\d+$")
2108 .expect("valid regex")
2109 .fail_fast(true);
2110
2111 let result = validator.validate(&json!("ab"), "code");
2112 assert!(!result.is_valid());
2113 assert_eq!(result.errors().len(), 1);
2114 assert_eq!(result.errors()[0].code, codes::MIN_LENGTH);
2115
2116 let result_default = validators::string()
2117 .min(5)
2118 .try_pattern(r"^\d+$")
2119 .expect("valid regex")
2120 .validate(&json!("ab"), "code");
2121 assert_eq!(result_default.errors().len(), 2);
2122 }
2123
2124 #[test]
2125 fn test_fail_fast_propagated_after_fields_added() {
2126 let validator = validators::map()
2127 .field("name", validators::string().min(2))
2128 .field("age", validators::int().min(0))
2129 .fail_fast(true);
2130
2131 let result = validator.validate(&json!({"name": "x", "age": -1}), "user");
2132 assert!(!result.is_valid());
2133 assert_eq!(result.errors().len(), 1);
2134 }
2135
2136 #[test]
2137 fn test_uuid_validator() {
2138 let validator = validators::uuid();
2139 assert!(validator
2140 .validate(&json!("550e8400-e29b-41d4-a716-446655440000"), "id")
2141 .is_valid());
2142
2143 let result = validator.validate(&json!("not-a-uuid"), "id");
2144 assert!(!result.is_valid());
2145 assert_eq!(result.errors()[0].code, codes::UUID);
2146 assert_eq!(result.errors()[0].message, "Invalid UUID: not-a-uuid");
2147
2148 let result = validator.validate(&json!(42), "id");
2149 assert_eq!(result.errors()[0].code, codes::TYPE);
2150 assert_eq!(result.errors()[0].message, "Expected string, got integer");
2151 }
2152
2153 #[test]
2154 fn test_date_validator() {
2155 let validator = validators::date();
2156 assert!(validator.validate(&json!("2026-09-07"), "d").is_valid());
2157
2158 let result = validator.validate(&json!("2026-13-07"), "d");
2159 assert_eq!(result.errors()[0].code, codes::DATE);
2160 assert_eq!(result.errors()[0].message, "Invalid date: 2026-13-07");
2161 }
2162
2163 #[test]
2164 fn test_datetime_validator() {
2165 let validator = validators::datetime();
2166 assert!(validator
2167 .validate(&json!("2026-09-07T10:30:00Z"), "t")
2168 .is_valid());
2169 assert!(validator
2170 .validate(&json!("2026-09-07T10:30:00.5+05:30"), "t")
2171 .is_valid());
2172
2173 let result = validator.validate(&json!("2026-09-07 10:30"), "t");
2174 assert_eq!(result.errors()[0].code, codes::DATETIME);
2175 assert_eq!(
2176 result.errors()[0].message,
2177 "Invalid datetime: 2026-09-07 10:30"
2178 );
2179 }
2180
2181 #[test]
2182 fn test_numeric_validator() {
2183 let validator = validators::numeric();
2184 assert!(validator.validate(&json!("-12.5"), "n").is_valid());
2185 assert!(validator.validate(&json!("1e3"), "n").is_valid());
2186
2187 let result = validator.validate(&json!("12a"), "n");
2188 assert_eq!(result.errors()[0].code, codes::NUMERIC);
2189 assert_eq!(
2190 result.errors()[0].message,
2191 "Expected numeric string, got 12a"
2192 );
2193
2194 let result = validator.validate(&json!(12), "n");
2195 assert_eq!(result.errors()[0].code, codes::TYPE);
2196 }
2197
2198 #[test]
2199 fn test_not_empty_validator() {
2200 let validator = validators::not_empty();
2201 assert!(validator.validate(&json!("x"), "v").is_valid());
2202 assert!(validator.validate(&json!([1]), "v").is_valid());
2203 assert!(validator.validate(&json!({"k": 1}), "v").is_valid());
2204
2205 for bad in [json!(""), json!([]), json!({})] {
2206 let result = validator.validate(&bad, "v");
2207 assert_eq!(result.errors()[0].code, codes::NOT_EMPTY);
2208 assert_eq!(result.errors()[0].message, "Value must not be empty");
2209 }
2210
2211 let result = validator.validate(&json!(5), "v");
2212 assert_eq!(result.errors()[0].code, codes::TYPE);
2213 assert_eq!(
2214 result.errors()[0].message,
2215 "Expected string, array, or object, got integer"
2216 );
2217 }
2218
2219 #[test]
2220 fn test_enum_validator() {
2221 let validator = validators::enum_values(vec![json!("a"), json!(1), json!(true)]);
2222 assert!(validator.validate(&json!("a"), "v").is_valid());
2223 assert!(validator.validate(&json!(1), "v").is_valid());
2224
2225 let result = validator.validate(&json!("b"), "v");
2226 assert_eq!(result.errors()[0].code, codes::ENUM);
2227 assert_eq!(
2228 result.errors()[0].message,
2229 "Value must be one of \"a\", 1, true, got \"b\""
2230 );
2231 }
2232
2233 #[test]
2234 fn test_one_of_validator() {
2235 let validator = validators::one_of(vec![
2236 Box::new(validators::string().min(3)),
2237 Box::new(validators::int().min(10)),
2238 ]);
2239 assert!(validator.validate(&json!("abc"), "v").is_valid());
2240 assert!(validator.validate(&json!(15), "v").is_valid());
2241
2242 let result = validator.validate(&json!(5), "v");
2243 assert!(!result.is_valid());
2244 assert_eq!(result.errors().len(), 1);
2245 assert_eq!(result.errors()[0].code, codes::ONE_OF);
2246 assert_eq!(
2247 result.errors()[0].message,
2248 "Value does not match any allowed schema"
2249 );
2250 }
2251
2252 #[test]
2253 fn test_regex_factory() {
2254 let validator = validators::regex(Regex::new(r"^[a-z]+$").unwrap());
2255 assert!(validator.validate(&json!("abc"), "code").is_valid());
2256 assert!(!validator.validate(&json!("ABC"), "code").is_valid());
2257 }
2258
2259 #[test]
2260 fn test_sensitive_redacts_value() {
2261 let result = validators::email()
2264 .sensitive(true)
2265 .validate(&json!("p@ssw0rd"), "secret");
2266 assert!(!result.is_valid());
2267 assert_eq!(result.errors()[0].message, "Invalid email address: ***");
2268 assert!(result.errors()[0].value.is_none());
2269
2270 let result = validators::uuid()
2271 .sensitive(true)
2272 .validate(&json!("leaked"), "id");
2273 assert_eq!(result.errors()[0].message, "Invalid UUID: ***");
2274 assert!(result.errors()[0].value.is_none());
2275
2276 let result = validators::string()
2278 .choices(vec!["a".to_string(), "b".to_string()])
2279 .sensitive(true)
2280 .validate(&json!("hunter2"), "token");
2281 assert_eq!(
2282 result.errors()[0].message,
2283 "Value must be one of a, b, got '***'"
2284 );
2285 assert!(result.errors()[0].value.is_none());
2286
2287 let result = validators::enum_values(vec![json!("a"), json!(1)])
2289 .sensitive(true)
2290 .validate(&json!("hunter2"), "token");
2291 assert_eq!(
2292 result.errors()[0].message,
2293 "Value must be one of \"a\", 1, got ***"
2294 );
2295 assert!(result.errors()[0].value.is_none());
2296 }
2297
2298 #[test]
2299 fn test_sensitive_other_messages_unchanged() {
2300 let result = validators::string()
2302 .min(5)
2303 .sensitive(true)
2304 .validate(&json!("abc"), "secret");
2305 assert_eq!(
2306 result.errors()[0].message,
2307 "String length must be at least 5, got 3"
2308 );
2309 assert!(result.errors()[0].value.is_none());
2310
2311 let result = validators::map()
2313 .sensitive(true)
2314 .field("inner", validators::email())
2315 .validate(&json!({"inner": "not-an-email"}), "user");
2316 assert_eq!(
2317 result.errors()[0].message,
2318 "Invalid email address: not-an-email"
2319 );
2320 }
2321
2322 #[test]
2323 fn test_pattern_input_length_cap() {
2324 let long = "a".repeat(MAX_PATTERN_INPUT_LENGTH + 1);
2327
2328 let result = validators::string()
2329 .try_pattern(r"^a+$")
2330 .unwrap()
2331 .validate(&json!(long), "s");
2332 assert!(!result.is_valid());
2333 assert_eq!(result.errors()[0].code, codes::PATTERN);
2334
2335 let result = validators::email().validate(&json!(long), "e");
2336 assert_eq!(result.errors()[0].code, codes::EMAIL);
2337
2338 let result = validators::numeric().validate(&json!(long), "n");
2339 assert_eq!(result.errors()[0].code, codes::NUMERIC);
2340
2341 let at_limit = "a".repeat(MAX_PATTERN_INPUT_LENGTH);
2343 assert!(validators::string()
2344 .try_pattern(r"^a+$")
2345 .unwrap()
2346 .validate(&json!(at_limit), "s")
2347 .is_valid());
2348 }
2349
2350 #[test]
2351 fn test_try_validate() {
2352 let schema = Schema::new().field("name", validators::string());
2353 assert!(schema.try_validate(&json!({"name": "Ada"})).is_ok());
2354
2355 let err = schema.try_validate(&json!({})).unwrap_err();
2356 assert_eq!(err.0.len(), 1);
2357 assert_eq!(err.to_string(), "name: Field is required");
2358 }
2359}