1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
//! Validation attributes for facet.
//!
//! This crate provides validation attributes that can be used with the `#[facet(...)]` syntax.
//! Validators are run during deserialization, providing errors with spans that point to the
//! problematic JSON location.
//!
//! # Example
//!
//! ```ignore
//! use facet::Facet;
//!
//! #[derive(Facet)]
//! pub struct Product {
//! #[facet(validate::min_length = 1, validate::max_length = 100)]
//! pub title: String,
//!
//! #[facet(validate::min = 0)]
//! pub price: i64,
//!
//! #[facet(validate::email)]
//! pub contact_email: String,
//!
//! #[facet(validate::custom = validate_currency)]
//! pub currency: String,
//! }
//!
//! fn validate_currency(s: &str) -> Result<(), String> {
//! match s {
//! "USD" | "EUR" | "GBP" => Ok(()),
//! _ => Err(format!("invalid currency code: {}", s)),
//! }
//! }
//! ```
//!
//! # Built-in Validators
//!
//! | Validator | Syntax | Applies To |
//! |-----------|--------|------------|
//! | `min` | `validate::min = 0` | numbers |
//! | `max` | `validate::max = 100` | numbers |
//! | `min_length` | `validate::min_length = 1` | String, Vec, slices |
//! | `max_length` | `validate::max_length = 100` | String, Vec, slices |
//! | `email` | `validate::email` | String |
//! | `url` | `validate::url` | String |
//! | `regex` | `validate::regex = r"..."` | String |
//! | `contains` | `validate::contains = "foo"` | String |
//! | `custom` | `validate::custom = fn_name` | any |
use Regex;
use LazyLock;
// Re-export the validator function type for use in custom validators
pub use ValidatorFn;
/// Validates that a string is a valid email address.
///
/// Uses a simple regex pattern that catches most common cases.
/// Validates that a string is a valid URL.
///
/// Uses a simple regex pattern that catches most common cases.
/// Validates that a string matches a regex pattern.
// Define the validation attribute grammar
define_attr_grammar!