vld 0.3.0

Type-safe runtime validation library for Rust, inspired by Zod
Documentation
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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
use serde_json::Value;

use crate::error::{value_type_name, IssueCode, VldError};
use crate::schema::VldSchema;

/// Schema for date validation. Parses ISO 8601 date strings (`YYYY-MM-DD`)
/// into [`chrono::NaiveDate`].
///
/// Created via [`vld::date()`](crate::date).
///
/// # Example
/// ```ignore
/// use vld::prelude::*;
///
/// let schema = vld::date().min("2020-01-01").max("2030-12-31");
/// let d = schema.parse(r#""2024-06-15""#).unwrap();
/// assert_eq!(d.to_string(), "2024-06-15");
/// ```
#[derive(Clone)]
pub struct ZDate {
    min: Option<(chrono::NaiveDate, String)>,
    max: Option<(chrono::NaiveDate, String)>,
    past: Option<String>,
    future: Option<String>,
    custom_type_error: Option<String>,
}

impl ZDate {
    pub fn new() -> Self {
        Self {
            min: None,
            max: None,
            past: None,
            future: None,
            custom_type_error: None,
        }
    }

    /// Set a custom error message for type/format mismatch.
    pub fn type_error(mut self, msg: impl Into<String>) -> Self {
        self.custom_type_error = Some(msg.into());
        self
    }

    /// Minimum date (inclusive). Accepts `"YYYY-MM-DD"` string.
    pub fn min(self, date: &str) -> Self {
        let d = chrono::NaiveDate::parse_from_str(date, "%Y-%m-%d")
            .unwrap_or_else(|_| panic!("Invalid date literal: {}", date));
        self.min_date(d)
    }

    /// Minimum date (inclusive) from a `NaiveDate`.
    pub fn min_date(mut self, date: chrono::NaiveDate) -> Self {
        let msg = format!("Date must be on or after {}", date);
        self.min = Some((date, msg));
        self
    }

    /// Maximum date (inclusive). Accepts `"YYYY-MM-DD"` string.
    pub fn max(self, date: &str) -> Self {
        let d = chrono::NaiveDate::parse_from_str(date, "%Y-%m-%d")
            .unwrap_or_else(|_| panic!("Invalid date literal: {}", date));
        self.max_date(d)
    }

    /// Maximum date (inclusive) from a `NaiveDate`.
    pub fn max_date(mut self, date: chrono::NaiveDate) -> Self {
        let msg = format!("Date must be on or before {}", date);
        self.max = Some((date, msg));
        self
    }

    /// Date must be in the past (before today).
    pub fn past(self) -> Self {
        self.past_msg("Date must be in the past")
    }

    /// Date must be in the past (before today), with custom message.
    pub fn past_msg(mut self, msg: impl Into<String>) -> Self {
        self.past = Some(msg.into());
        self
    }

    /// Date must be in the future (after today).
    pub fn future(self) -> Self {
        self.future_msg("Date must be in the future")
    }

    /// Date must be in the future (after today), with custom message.
    pub fn future_msg(mut self, msg: impl Into<String>) -> Self {
        self.future = Some(msg.into());
        self
    }

    /// Generate a JSON Schema representation.
    #[cfg(feature = "openapi")]
    pub fn to_json_schema(&self) -> serde_json::Value {
        serde_json::json!({"type": "string", "format": "date"})
    }
}

impl Default for ZDate {
    fn default() -> Self {
        Self::new()
    }
}

impl VldSchema for ZDate {
    type Output = chrono::NaiveDate;

    fn parse_value(&self, value: &Value) -> Result<chrono::NaiveDate, VldError> {
        let s = value.as_str().ok_or_else(|| {
            let msg = self.custom_type_error.clone().unwrap_or_else(|| {
                format!(
                    "Expected date string (YYYY-MM-DD), received {}",
                    value_type_name(value)
                )
            });
            VldError::single_with_value(
                IssueCode::InvalidType {
                    expected: "string (date)".to_string(),
                    received: value_type_name(value),
                },
                msg,
                value,
            )
        })?;

        let date = chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d").map_err(|_| {
            VldError::single_with_value(
                IssueCode::Custom {
                    code: "invalid_date".to_string(),
                },
                format!("Invalid date format: expected YYYY-MM-DD, got \"{}\"", s),
                value,
            )
        })?;

        let mut errors = VldError::new();

        if let Some((min_date, msg)) = &self.min {
            if date < *min_date {
                errors.push_with_value(
                    IssueCode::TooSmall {
                        minimum: 0.0,
                        inclusive: true,
                    },
                    msg.clone(),
                    value,
                );
            }
        }
        if let Some((max_date, msg)) = &self.max {
            if date > *max_date {
                errors.push_with_value(
                    IssueCode::TooBig {
                        maximum: 0.0,
                        inclusive: true,
                    },
                    msg.clone(),
                    value,
                );
            }
        }
        let today = chrono::Utc::now().date_naive();
        if let Some(msg) = &self.past {
            if date >= today {
                errors.push_with_value(
                    IssueCode::Custom {
                        code: "not_past_date".to_string(),
                    },
                    msg.clone(),
                    value,
                );
            }
        }
        if let Some(msg) = &self.future {
            if date <= today {
                errors.push_with_value(
                    IssueCode::Custom {
                        code: "not_future_date".to_string(),
                    },
                    msg.clone(),
                    value,
                );
            }
        }

        if errors.is_empty() {
            Ok(date)
        } else {
            Err(errors)
        }
    }
}

/// Schema for datetime validation. Parses ISO 8601 datetime strings
/// into [`chrono::DateTime<chrono::Utc>`].
///
/// Created via [`vld::datetime()`](crate::datetime).
///
/// Accepts formats like:
/// - `2024-01-15T10:30:00Z`
/// - `2024-01-15T10:30:00+03:00`
/// - `2024-01-15T10:30:00.123Z`
///
/// # Example
/// ```ignore
/// use vld::prelude::*;
///
/// let schema = vld::datetime();
/// let dt = schema.parse(r#""2024-06-15T12:00:00Z""#).unwrap();
/// ```
#[derive(Clone)]
pub struct ZDateTime {
    min: Option<(chrono::DateTime<chrono::Utc>, String)>,
    max: Option<(chrono::DateTime<chrono::Utc>, String)>,
    past: Option<String>,
    future: Option<String>,
    allow_naive: bool,
    naive_offset: chrono::FixedOffset,
    required_timezone_offset: Option<(chrono::FixedOffset, String)>,
    custom_type_error: Option<String>,
}

impl ZDateTime {
    pub fn new() -> Self {
        Self {
            min: None,
            max: None,
            past: None,
            future: None,
            allow_naive: true,
            naive_offset: chrono::FixedOffset::east_opt(0).expect("0 offset must be valid"),
            required_timezone_offset: None,
            custom_type_error: None,
        }
    }

    /// Set a custom error message for type/format mismatch.
    pub fn type_error(mut self, msg: impl Into<String>) -> Self {
        self.custom_type_error = Some(msg.into());
        self
    }

    /// Minimum datetime (inclusive). Accepts RFC3339.
    pub fn min(self, dt: &str) -> Self {
        let parsed = chrono::DateTime::parse_from_rfc3339(dt)
            .unwrap_or_else(|_| panic!("Invalid datetime literal: {}", dt))
            .with_timezone(&chrono::Utc);
        self.min_datetime(parsed)
    }

    /// Minimum datetime (inclusive) from a UTC datetime.
    pub fn min_datetime(mut self, dt: chrono::DateTime<chrono::Utc>) -> Self {
        let msg = format!("Datetime must be on or after {}", dt.to_rfc3339());
        self.min = Some((dt, msg));
        self
    }

    /// Maximum datetime (inclusive). Accepts RFC3339.
    pub fn max(self, dt: &str) -> Self {
        let parsed = chrono::DateTime::parse_from_rfc3339(dt)
            .unwrap_or_else(|_| panic!("Invalid datetime literal: {}", dt))
            .with_timezone(&chrono::Utc);
        self.max_datetime(parsed)
    }

    /// Maximum datetime (inclusive) from a UTC datetime.
    pub fn max_datetime(mut self, dt: chrono::DateTime<chrono::Utc>) -> Self {
        let msg = format!("Datetime must be on or before {}", dt.to_rfc3339());
        self.max = Some((dt, msg));
        self
    }

    /// Datetime must be in the past.
    pub fn past(self) -> Self {
        self.past_msg("Datetime must be in the past")
    }

    /// Datetime must be in the past, with custom message.
    pub fn past_msg(mut self, msg: impl Into<String>) -> Self {
        self.past = Some(msg.into());
        self
    }

    /// Datetime must be in the future.
    pub fn future(self) -> Self {
        self.future_msg("Datetime must be in the future")
    }

    /// Datetime must be in the future, with custom message.
    pub fn future_msg(mut self, msg: impl Into<String>) -> Self {
        self.future = Some(msg.into());
        self
    }

    /// Allow or disallow naive datetime input without timezone.
    ///
    /// Default is `true` for backward compatibility.
    pub fn naive_allowed(mut self, allowed: bool) -> Self {
        self.allow_naive = allowed;
        self
    }

    /// Strict mode: require timezone in datetime input (RFC3339).
    pub fn with_timezone_only(self) -> Self {
        self.naive_allowed(false)
    }

    /// Interpret naive datetimes (`YYYY-MM-DDTHH:MM:SS`) in the provided timezone offset.
    ///
    /// The parsed output is still normalized to UTC.
    pub fn naive_timezone_offset(mut self, offset_seconds: i32) -> Self {
        let offset = chrono::FixedOffset::east_opt(offset_seconds).unwrap_or_else(|| {
            panic!(
                "Invalid timezone offset seconds: {} (expected range -86400..=86400)",
                offset_seconds
            )
        });
        self.naive_offset = offset;
        self
    }

    /// Require explicit timezone offset in the input to match `offset_seconds`.
    ///
    /// Applied only to RFC3339 inputs that include timezone.
    pub fn timezone_offset_only(self, offset_seconds: i32) -> Self {
        chrono::FixedOffset::east_opt(offset_seconds).unwrap_or_else(|| {
            panic!(
                "Invalid timezone offset seconds: {} (expected range -86400..=86400)",
                offset_seconds
            )
        });
        let sign = if offset_seconds >= 0 { '+' } else { '-' };
        let abs = offset_seconds.unsigned_abs();
        let hh = abs / 3600;
        let mm = (abs % 3600) / 60;
        let msg = format!("Timezone offset must be {}{:02}:{:02}", sign, hh, mm);
        self.timezone_offset_only_msg(offset_seconds, msg)
    }

    /// Same as [`timezone_offset_only`](Self::timezone_offset_only), with custom message.
    pub fn timezone_offset_only_msg(mut self, offset_seconds: i32, msg: impl Into<String>) -> Self {
        let offset = chrono::FixedOffset::east_opt(offset_seconds).unwrap_or_else(|| {
            panic!(
                "Invalid timezone offset seconds: {} (expected range -86400..=86400)",
                offset_seconds
            )
        });
        self.required_timezone_offset = Some((offset, msg.into()));
        self
    }

    /// Generate a JSON Schema representation.
    #[cfg(feature = "openapi")]
    pub fn to_json_schema(&self) -> serde_json::Value {
        serde_json::json!({"type": "string", "format": "date-time"})
    }
}

impl Default for ZDateTime {
    fn default() -> Self {
        Self::new()
    }
}

impl VldSchema for ZDateTime {
    type Output = chrono::DateTime<chrono::Utc>;

    fn parse_value(&self, value: &Value) -> Result<chrono::DateTime<chrono::Utc>, VldError> {
        let s = value.as_str().ok_or_else(|| {
            let msg = self.custom_type_error.clone().unwrap_or_else(|| {
                format!(
                    "Expected datetime string, received {}",
                    value_type_name(value)
                )
            });
            VldError::single_with_value(
                IssueCode::InvalidType {
                    expected: "string (datetime)".to_string(),
                    received: value_type_name(value),
                },
                msg,
                value,
            )
        })?;

        use chrono::TimeZone;

        let dt = if let Ok(dt_fixed) = chrono::DateTime::parse_from_rfc3339(s) {
            if let Some((required, msg)) = &self.required_timezone_offset {
                if dt_fixed.offset().local_minus_utc() != required.local_minus_utc() {
                    return Err(VldError::single_with_value(
                        IssueCode::Custom {
                            code: "invalid_timezone_offset".to_string(),
                        },
                        msg.clone(),
                        value,
                    ));
                }
            }
            dt_fixed.with_timezone(&chrono::Utc)
        } else if self.allow_naive {
            if let Ok(ndt) = chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S") {
                self.naive_offset
                    .from_local_datetime(&ndt)
                    .single()
                    .expect("FixedOffset must map local datetime unambiguously")
                    .with_timezone(&chrono::Utc)
            } else if let Ok(ndt) = chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S%.f")
            {
                self.naive_offset
                    .from_local_datetime(&ndt)
                    .single()
                    .expect("FixedOffset must map local datetime unambiguously")
                    .with_timezone(&chrono::Utc)
            } else {
                return Err(VldError::single_with_value(
                    IssueCode::Custom {
                        code: "invalid_datetime".to_string(),
                    },
                    format!("Invalid datetime format: \"{}\"", s),
                    value,
                ));
            }
        } else {
            return Err(VldError::single_with_value(
                IssueCode::Custom {
                    code: "invalid_datetime".to_string(),
                },
                format!("Invalid datetime format: \"{}\"", s),
                value,
            ));
        };

        let mut errors = VldError::new();
        if let Some((min_dt, msg)) = &self.min {
            if dt < *min_dt {
                errors.push_with_value(
                    IssueCode::TooSmall {
                        minimum: 0.0,
                        inclusive: true,
                    },
                    msg.clone(),
                    value,
                );
            }
        }
        if let Some((max_dt, msg)) = &self.max {
            if dt > *max_dt {
                errors.push_with_value(
                    IssueCode::TooBig {
                        maximum: 0.0,
                        inclusive: true,
                    },
                    msg.clone(),
                    value,
                );
            }
        }
        let now = chrono::Utc::now();
        if let Some(msg) = &self.past {
            if dt >= now {
                errors.push_with_value(
                    IssueCode::Custom {
                        code: "not_past_datetime".to_string(),
                    },
                    msg.clone(),
                    value,
                );
            }
        }
        if let Some(msg) = &self.future {
            if dt <= now {
                errors.push_with_value(
                    IssueCode::Custom {
                        code: "not_future_datetime".to_string(),
                    },
                    msg.clone(),
                    value,
                );
            }
        }

        if errors.is_empty() {
            Ok(dt)
        } else {
            Err(errors)
        }
    }
}