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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
use std::fmt;

/// A segment in a validation error path.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
pub enum PathSegment {
    /// Object field name.
    Field(String),
    /// Array index.
    Index(usize),
}

impl fmt::Display for PathSegment {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            PathSegment::Field(name) => write!(f, ".{}", name),
            PathSegment::Index(idx) => write!(f, "[{}]", idx),
        }
    }
}

/// Type of string validation that failed.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
pub enum StringValidation {
    Email,
    Url,
    UrlStrict,
    Uri,
    Uuid,
    UuidV1,
    UuidV4,
    UuidV7,
    Ip,
    Slug,
    Color,
    Currency,
    CountryCode,
    Locale,
    Cron,
    Regex,
    StartsWith,
    EndsWith,
    Ipv4,
    Ipv6,
    Cidr,
    Mac,
    Hex,
    CreditCard,
    Phone,
    PhoneE164,
    Semver,
    SemverFull,
    Jwt,
    Ascii,
    Alpha,
    Alphanumeric,
    Lowercase,
    Uppercase,
    Base64,
    IsoDate,
    IsoDatetime,
    IsoTime,
    Hostname,
    Cuid2,
    Ulid,
    Nanoid,
    Emoji,
}

/// Validation issue code — describes what went wrong.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
pub enum IssueCode {
    InvalidType { expected: String, received: String },
    TooSmall { minimum: f64, inclusive: bool },
    TooBig { maximum: f64, inclusive: bool },
    InvalidString { validation: StringValidation },
    NotInt,
    NotFinite,
    MissingField,
    UnrecognizedField,
    IoError,
    ParseError,
    Custom { code: String },
}

/// A single validation issue with path, message and received value.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
pub struct ValidationIssue {
    pub code: IssueCode,
    pub message: String,
    pub path: Vec<PathSegment>,
    /// The value that was received (if available).
    pub received: Option<serde_json::Value>,
}

/// Collection of validation errors.
///
/// Errors are accumulated (not short-circuited), so all issues are reported at once.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
pub struct VldError {
    pub issues: Vec<ValidationIssue>,
}

impl VldError {
    /// Create an empty error container.
    pub fn new() -> Self {
        Self { issues: vec![] }
    }

    /// Create an error with a single issue (no received value).
    pub fn single(code: IssueCode, message: impl Into<String>) -> Self {
        Self {
            issues: vec![ValidationIssue {
                code,
                message: message.into(),
                path: vec![],
                received: None,
            }],
        }
    }

    /// Create an error with a single issue and the received value.
    pub fn single_with_value(
        code: IssueCode,
        message: impl Into<String>,
        received: &serde_json::Value,
    ) -> Self {
        Self {
            issues: vec![ValidationIssue {
                code,
                message: message.into(),
                path: vec![],
                received: Some(truncate_value(received)),
            }],
        }
    }

    /// Prepend a path segment to all issues (used for nested objects/arrays).
    pub fn with_prefix(mut self, segment: PathSegment) -> Self {
        for issue in &mut self.issues {
            issue.path.insert(0, segment.clone());
        }
        self
    }

    /// Merge another error's issues into this one.
    pub fn merge(mut self, other: VldError) -> Self {
        self.issues.extend(other.issues);
        self
    }

    /// Check if there are no issues.
    pub fn is_empty(&self) -> bool {
        self.issues.is_empty()
    }

    /// Push a single issue (no received value).
    pub fn push(&mut self, code: IssueCode, message: impl Into<String>) {
        self.issues.push(ValidationIssue {
            code,
            message: message.into(),
            path: vec![],
            received: None,
        });
    }

    /// Push a single issue with the received value.
    pub fn push_with_value(
        &mut self,
        code: IssueCode,
        message: impl Into<String>,
        received: &serde_json::Value,
    ) {
        self.issues.push(ValidationIssue {
            code,
            message: message.into(),
            path: vec![],
            received: Some(truncate_value(received)),
        });
    }
}

/// Fluent builder for constructing a single [`ValidationIssue`].
///
/// Obtained via [`VldError::issue()`]. Push it into a `VldError` with
/// [`.finish()`](IssueBuilder::finish).
///
/// # Example
/// ```
/// use vld::prelude::*;
///
/// let mut errors = VldError::new();
/// errors
///     .issue(IssueCode::Custom { code: "password_weak".into() })
///     .message("Password is too weak")
///     .path_field("password")
///     .received(&serde_json::json!("123"))
///     .finish();
/// assert_eq!(errors.issues.len(), 1);
/// assert_eq!(errors.issues[0].message, "Password is too weak");
/// ```
pub struct IssueBuilder<'a> {
    errors: &'a mut VldError,
    code: IssueCode,
    message: Option<String>,
    path: Vec<PathSegment>,
    received: Option<serde_json::Value>,
}

impl<'a> IssueBuilder<'a> {
    /// Set the error message.
    pub fn message(mut self, msg: impl Into<String>) -> Self {
        self.message = Some(msg.into());
        self
    }

    /// Add a field path segment.
    pub fn path_field(mut self, name: impl Into<String>) -> Self {
        self.path.push(PathSegment::Field(name.into()));
        self
    }

    /// Add an index path segment.
    pub fn path_index(mut self, idx: usize) -> Self {
        self.path.push(PathSegment::Index(idx));
        self
    }

    /// Attach the received value.
    pub fn received(mut self, value: &serde_json::Value) -> Self {
        self.received = Some(truncate_value(value));
        self
    }

    /// Finish building and push the issue into the parent `VldError`.
    pub fn finish(self) {
        let msg = self
            .message
            .unwrap_or_else(|| format!("Validation error: {}", self.code.key()));
        self.errors.issues.push(ValidationIssue {
            code: self.code,
            message: msg,
            path: self.path,
            received: self.received,
        });
    }
}

impl VldError {
    /// Start building a new issue with the fluent API.
    ///
    /// Call `.message(...)`, `.path_field(...)`, `.received(...)` etc., then
    /// `.finish()` to push the issue.
    ///
    /// # Example
    /// ```
    /// use vld::prelude::*;
    ///
    /// let mut errors = VldError::new();
    /// errors
    ///     .issue(IssueCode::Custom { code: "my_check".into() })
    ///     .message("something went wrong")
    ///     .path_field("field_name")
    ///     .finish();
    /// ```
    pub fn issue(&mut self, code: IssueCode) -> IssueBuilder<'_> {
        IssueBuilder {
            errors: self,
            code,
            message: None,
            path: vec![],
            received: None,
        }
    }
}

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

impl fmt::Display for VldError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for (i, issue) in self.issues.iter().enumerate() {
            if i > 0 {
                writeln!(f)?;
            }
            if !issue.path.is_empty() {
                let path_str: String = issue.path.iter().map(|p| p.to_string()).collect();
                write!(f, "{}: ", path_str)?;
            }
            write!(f, "{}", issue.message)?;
            if let Some(val) = &issue.received {
                write!(f, ", received {}", format_value_short(val))?;
            }
        }
        Ok(())
    }
}

impl std::error::Error for VldError {}

impl IssueCode {
    /// Stable string key for this error code. Useful for i18n and error mapping.
    pub fn key(&self) -> &str {
        match self {
            IssueCode::InvalidType { .. } => "invalid_type",
            IssueCode::TooSmall { .. } => "too_small",
            IssueCode::TooBig { .. } => "too_big",
            IssueCode::InvalidString { .. } => "invalid_string",
            IssueCode::NotInt => "not_int",
            IssueCode::NotFinite => "not_finite",
            IssueCode::MissingField => "missing_field",
            IssueCode::UnrecognizedField => "unrecognized_field",
            IssueCode::IoError => "io_error",
            IssueCode::ParseError => "parse_error",
            IssueCode::Custom { code } => code,
        }
    }

    /// Extract key-value parameters from this error code for message formatting.
    ///
    /// Useful for i18n: format templates like `"Must be at least {minimum}"`.
    pub fn params(&self) -> Vec<(&str, String)> {
        match self {
            IssueCode::InvalidType { expected, received } => {
                vec![
                    ("expected", expected.clone()),
                    ("received", received.clone()),
                ]
            }
            IssueCode::TooSmall { minimum, inclusive } => {
                vec![
                    ("minimum", minimum.to_string()),
                    ("inclusive", inclusive.to_string()),
                ]
            }
            IssueCode::TooBig { maximum, inclusive } => {
                vec![
                    ("maximum", maximum.to_string()),
                    ("inclusive", inclusive.to_string()),
                ]
            }
            IssueCode::InvalidString { validation } => {
                vec![("validation", format!("{:?}", validation))]
            }
            _ => vec![],
        }
    }
}

/// Returns the JSON type name for a value.
#[doc(hidden)]
pub fn value_type_name(value: &serde_json::Value) -> String {
    match value {
        serde_json::Value::Null => "null",
        serde_json::Value::Bool(_) => "boolean",
        serde_json::Value::Number(_) => "number",
        serde_json::Value::String(_) => "string",
        serde_json::Value::Array(_) => "array",
        serde_json::Value::Object(_) => "object",
    }
    .to_string()
}

/// Format a JSON value for display in errors (short form).
pub fn format_value_short(value: &serde_json::Value) -> String {
    match value {
        serde_json::Value::Null => "null".to_string(),
        serde_json::Value::Bool(b) => b.to_string(),
        serde_json::Value::Number(n) => n.to_string(),
        serde_json::Value::String(s) => {
            let char_count = s.chars().count();
            if char_count > 50 {
                let prefix: String = s.chars().take(47).collect();
                format!("\"{}...\"", prefix)
            } else {
                format!("\"{}\"", s)
            }
        }
        serde_json::Value::Array(arr) => format!("Array(len={})", arr.len()),
        serde_json::Value::Object(obj) => format!("Object(keys={})", obj.len()),
    }
}

/// Result of validating a single field.
///
/// Returned by `validate_fields()` generated by the [`schema!`](crate::schema!) macro.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
pub struct FieldResult {
    /// Field name.
    pub name: String,
    /// Raw input value (before validation).
    pub input: serde_json::Value,
    /// `Ok(json_value)` if the field is valid (output serialized to JSON),
    /// `Err(error)` if validation failed.
    pub result: Result<serde_json::Value, VldError>,
}

impl FieldResult {
    /// Whether this field passed validation.
    pub fn is_ok(&self) -> bool {
        self.result.is_ok()
    }

    /// Whether this field failed validation.
    pub fn is_err(&self) -> bool {
        self.result.is_err()
    }
}

impl std::fmt::Display for FieldResult {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.result {
            Ok(v) => write!(f, "{}: {}", self.name, format_value_short(v)),
            Err(e) => {
                let received = format_value_short(&self.input);
                for (i, issue) in e.issues.iter().enumerate() {
                    if i > 0 {
                        writeln!(f)?;
                    }
                    write!(
                        f,
                        "{}: {} (received: {})",
                        self.name, issue.message, received
                    )?;
                }
                Ok(())
            }
        }
    }
}

/// Result of lenient parsing: contains the (possibly partial) struct and
/// per-field diagnostics.
///
/// Created by `parse_lenient()` / `parse_lenient_value()` generated by
/// [`impl_validate_fields!`](crate::impl_validate_fields).
///
/// The struct is always constructed — invalid fields fall back to
/// `Default::default()`. You can inspect which fields passed/failed via
/// [`fields()`](Self::fields), and save the result to a file at any time
/// via `save_to_file()` (requires the `serialize` feature).
#[derive(Debug)]
pub struct ParseResult<T> {
    /// The constructed struct (invalid fields use `Default`).
    pub value: T,
    /// Per-field validation diagnostics.
    field_results: Vec<FieldResult>,
}

impl<T> ParseResult<T> {
    /// Create a new parse result.
    pub fn new(value: T, field_results: Vec<FieldResult>) -> Self {
        Self {
            value,
            field_results,
        }
    }

    /// All per-field results.
    pub fn fields(&self) -> &[FieldResult] {
        &self.field_results
    }

    /// Get a specific field's result by name.
    ///
    /// Returns `None` if no field with that name exists.
    pub fn field(&self, name: &str) -> Option<&FieldResult> {
        self.field_results.iter().find(|f| f.name == name)
    }

    /// Only the fields that passed validation.
    pub fn valid_fields(&self) -> Vec<&FieldResult> {
        self.field_results.iter().filter(|f| f.is_ok()).collect()
    }

    /// Only the fields that failed validation.
    pub fn error_fields(&self) -> Vec<&FieldResult> {
        self.field_results.iter().filter(|f| f.is_err()).collect()
    }

    /// Whether all fields passed validation.
    pub fn is_valid(&self) -> bool {
        self.field_results.iter().all(|f| f.is_ok())
    }

    /// Whether at least one field failed.
    pub fn has_errors(&self) -> bool {
        self.field_results.iter().any(|f| f.is_err())
    }

    /// Number of valid fields.
    pub fn valid_count(&self) -> usize {
        self.field_results.iter().filter(|f| f.is_ok()).count()
    }

    /// Number of invalid fields.
    pub fn error_count(&self) -> usize {
        self.field_results.iter().filter(|f| f.is_err()).count()
    }

    /// Consume and return the inner struct.
    pub fn into_value(self) -> T {
        self.value
    }

    /// Consume and return both the struct and field results.
    pub fn into_parts(self) -> (T, Vec<FieldResult>) {
        (self.value, self.field_results)
    }
}

#[cfg(feature = "serialize")]
impl<T: serde::Serialize> ParseResult<T> {
    /// Serialize the struct to a JSON file.
    ///
    /// Requires the `serialize` and `std` features.
    #[cfg(feature = "std")]
    pub fn save_to_file(&self, path: &std::path::Path) -> std::io::Result<()> {
        let json = serde_json::to_string_pretty(&self.value)
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
        std::fs::write(path, json)
    }

    /// Serialize the struct to a JSON string.
    ///
    /// Requires the `serialize` feature.
    pub fn to_json_string(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(&self.value)
    }

    /// Serialize the struct to a `serde_json::Value`.
    ///
    /// Requires the `serialize` feature.
    pub fn to_json_value(&self) -> Result<serde_json::Value, serde_json::Error> {
        serde_json::to_value(&self.value)
    }
}

impl<T: std::fmt::Debug> std::fmt::Display for ParseResult<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(
            f,
            "ParseResult ({} valid, {} errors):",
            self.valid_count(),
            self.error_count()
        )?;
        for field in &self.field_results {
            writeln!(f, "  {}", field)?;
        }
        Ok(())
    }
}

/// Truncate large values to avoid storing huge payloads in errors.
fn truncate_value(value: &serde_json::Value) -> serde_json::Value {
    match value {
        serde_json::Value::String(s) if s.len() > 100 => {
            serde_json::Value::String(format!("{}...", &s[..97]))
        }
        serde_json::Value::Array(arr) if arr.len() > 5 => {
            let mut truncated: Vec<serde_json::Value> = arr[..5].to_vec();
            truncated.push(serde_json::Value::String(format!(
                "... ({} more)",
                arr.len() - 5
            )));
            serde_json::Value::Array(truncated)
        }
        _ => value.clone(),
    }
}