catfive 0.2.0

Category-5 fluent, zero-dependency schema and form validation for Rust.
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
use crate::error::ValidationError;
use crate::format_helper::format_template;
use crate::spek::{parse_spek, validate_spek_kind};
use crate::traits::Validator;
use std::collections::HashSet;
use std::net::IpAddr;
use std::sync::Arc;

type Rule = Arc<dyn Fn(&str) -> Option<ValidationError> + Send + Sync>;

/// Fluent validator for string values.
#[derive(Clone, Default)]
pub struct StringValidator {
    rules: Vec<Rule>,
}

impl StringValidator {
    /// Creates a new empty string validator.
    pub fn new() -> Self {
        Self { rules: Vec::new() }
    }

    /// Enforces a specification pattern like `"[CPF]"`, `"[CNPJ]"`, `"[LUHN]"`, `"[HEX]"`, `"[ASCII 65..90]"`, or `"[ABC234]"`.
    ///
    /// # Example
    /// ```rust
    /// use catfive::string;
    ///
    /// let cpf_val = string().spek("[CPF]");
    /// let cnpj_val = string().spek("[CNPJ]").block(";@#");
    /// let hex_val = string().spek("[HEX]");
    /// let ascii_val = string().spek("[ASCII 65..90]");
    /// let custom_val = string().spek("[ABC234]");
    /// ```
    pub fn spek(self, spec: &str) -> Self {
        self.spek_internal(spec, None)
    }

    /// Enforces a specification pattern with a custom message template.
    pub fn spek_msg(self, spec: &str, msg_template: &str) -> Self {
        self.spek_internal(spec, Some(msg_template.to_string()))
    }

    fn spek_internal(mut self, spec: &str, custom_msg: Option<String>) -> Self {
        match parse_spek(spec) {
            Ok(kind) => {
                self.rules.push(Arc::new(move |val| {
                    validate_spek_kind(&kind, val, custom_msg.as_deref())
                }));
            }
            Err(e) => {
                let err_msg = e;
                self.rules.push(Arc::new(move |_| {
                    Some(ValidationError::new("invalid_spek_spec", err_msg.clone()))
                }));
            }
        }
        self
    }

    /// Enforces a minimum character length with default error message.
    pub fn min(self, min_len: usize) -> Self {
        self.min_msg(
            min_len,
            "Must be at least {min} characters long, got {count}",
        )
    }

    /// Enforces a minimum character length with a custom message template.
    ///
    /// Available placeholders: `{min}`, `{count}`, `{value}`.
    pub fn min_msg(mut self, min_len: usize, msg_template: &str) -> Self {
        let tpl = msg_template.to_string();
        self.rules.push(Arc::new(move |val| {
            let count = val.chars().count();
            if count < min_len {
                let msg = format_template(
                    &tpl,
                    &[
                        ("min", &min_len.to_string()),
                        ("count", &count.to_string()),
                        ("value", val),
                    ],
                );
                Some(ValidationError::new("min_length", msg))
            } else {
                None
            }
        }));
        self
    }

    /// Enforces a maximum character length with default error message.
    pub fn max(self, max_len: usize) -> Self {
        self.max_msg(max_len, "Must not exceed {max} characters, got {count}")
    }

    /// Enforces a maximum character length with a custom message template.
    ///
    /// Available placeholders: `{max}`, `{count}`, `{value}`.
    pub fn max_msg(mut self, max_len: usize, msg_template: &str) -> Self {
        let tpl = msg_template.to_string();
        self.rules.push(Arc::new(move |val| {
            let count = val.chars().count();
            if count > max_len {
                let msg = format_template(
                    &tpl,
                    &[
                        ("max", &max_len.to_string()),
                        ("count", &count.to_string()),
                        ("value", val),
                    ],
                );
                Some(ValidationError::new("max_length", msg))
            } else {
                None
            }
        }));
        self
    }

    /// Enforces an exact character length with default error message.
    pub fn length(self, exact_len: usize) -> Self {
        self.length_msg(
            exact_len,
            "Must be exactly {length} characters long, got {count}",
        )
    }

    /// Enforces an exact character length with a custom message template.
    ///
    /// Available placeholders: `{length}`, `{count}`, `{value}`.
    pub fn length_msg(mut self, exact_len: usize, msg_template: &str) -> Self {
        let tpl = msg_template.to_string();
        self.rules.push(Arc::new(move |val| {
            let count = val.chars().count();
            if count != exact_len {
                let msg = format_template(
                    &tpl,
                    &[
                        ("length", &exact_len.to_string()),
                        ("count", &count.to_string()),
                        ("value", val),
                    ],
                );
                Some(ValidationError::new("exact_length", msg))
            } else {
                None
            }
        }));
        self
    }

    /// Blocks specific characters from appearing in the string.
    ///
    /// Detailed error logs the exact forbidden character that was encountered.
    pub fn block(self, forbidden_chars: &str) -> Self {
        self.block_msg(forbidden_chars, "Character '{char}' is not allowed")
    }

    /// Blocks specific characters with a custom message template.
    ///
    /// Available placeholders: `{char}`, `{index}`, `{position}`, `{value}`.
    pub fn block_msg(mut self, forbidden_chars: &str, msg_template: &str) -> Self {
        let blocked: HashSet<char> = forbidden_chars.chars().collect();
        let tpl = msg_template.to_string();
        self.rules.push(Arc::new(move |val| {
            for (idx, ch) in val.chars().enumerate() {
                if blocked.contains(&ch) {
                    let ch_str = ch.to_string();
                    let idx_str = idx.to_string();
                    let pos_str = (idx + 1).to_string();
                    let msg = format_template(
                        &tpl,
                        &[
                            ("char", &ch_str),
                            ("index", &idx_str),
                            ("position", &pos_str),
                            ("value", val),
                        ],
                    );
                    return Some(ValidationError::new("blocked_char", msg));
                }
            }
            None
        }));
        self
    }

    /// Blocks specific characters with a custom closure.
    pub fn block_with<F>(mut self, forbidden_chars: &str, formatter: F) -> Self
    where
        F: Fn(char, usize) -> String + Send + Sync + 'static,
    {
        let blocked: HashSet<char> = forbidden_chars.chars().collect();
        self.rules.push(Arc::new(move |val| {
            for (idx, ch) in val.chars().enumerate() {
                if blocked.contains(&ch) {
                    let msg = formatter(ch, idx);
                    return Some(ValidationError::new("blocked_char", msg));
                }
            }
            None
        }));
        self
    }

    /// Requires the string to not be empty (or whitespace-only).
    pub fn not_empty(self) -> Self {
        self.not_empty_msg("Value cannot be empty")
    }

    /// Requires the string to not be empty with a custom message.
    pub fn not_empty_msg(mut self, msg: &str) -> Self {
        let err_msg = msg.to_string();
        self.rules.push(Arc::new(move |val| {
            if val.trim().is_empty() {
                Some(ValidationError::new("not_empty", err_msg.clone()))
            } else {
                None
            }
        }));
        self
    }

    /// Allows only characters present in the provided whitelist string.
    pub fn allow_only(self, allowed_chars: &str) -> Self {
        self.allow_only_msg(allowed_chars, "Character '{char}' is not allowed")
    }

    /// Allows only characters present in the provided whitelist string with custom message template.
    ///
    /// Available placeholders: `{char}`, `{index}`, `{position}`, `{value}`.
    pub fn allow_only_msg(mut self, allowed_chars: &str, msg_template: &str) -> Self {
        let allowed: HashSet<char> = allowed_chars.chars().collect();
        let tpl = msg_template.to_string();
        self.rules.push(Arc::new(move |val| {
            for (idx, ch) in val.chars().enumerate() {
                if !allowed.contains(&ch) {
                    let ch_str = ch.to_string();
                    let idx_str = idx.to_string();
                    let pos_str = (idx + 1).to_string();
                    let msg = format_template(
                        &tpl,
                        &[
                            ("char", &ch_str),
                            ("index", &idx_str),
                            ("position", &pos_str),
                            ("value", val),
                        ],
                    );
                    return Some(ValidationError::new("unallowed_char", msg));
                }
            }
            None
        }));
        self
    }

    /// Validates that the string is an alphanumeric string.
    pub fn alphanumeric(self) -> Self {
        self.alphanumeric_msg("Character '{char}' is not alphanumeric")
    }

    /// Validates that the string is alphanumeric with a custom message template.
    pub fn alphanumeric_msg(mut self, msg_template: &str) -> Self {
        let tpl = msg_template.to_string();
        self.rules.push(Arc::new(move |val| {
            for (idx, ch) in val.chars().enumerate() {
                if !ch.is_alphanumeric() {
                    let ch_str = ch.to_string();
                    let idx_str = idx.to_string();
                    let msg = format_template(
                        &tpl,
                        &[("char", &ch_str), ("index", &idx_str), ("value", val)],
                    );
                    return Some(ValidationError::new("alphanumeric", msg));
                }
            }
            None
        }));
        self
    }

    /// Validates that the string contains only alphabetic characters.
    pub fn alphabetic(self) -> Self {
        self.alphabetic_msg("Character '{char}' is not alphabetic")
    }

    /// Validates that the string contains only alphabetic characters with a custom message template.
    pub fn alphabetic_msg(mut self, msg_template: &str) -> Self {
        let tpl = msg_template.to_string();
        self.rules.push(Arc::new(move |val| {
            for (idx, ch) in val.chars().enumerate() {
                if !ch.is_alphabetic() {
                    let ch_str = ch.to_string();
                    let idx_str = idx.to_string();
                    let msg = format_template(
                        &tpl,
                        &[("char", &ch_str), ("index", &idx_str), ("value", val)],
                    );
                    return Some(ValidationError::new("alphabetic", msg));
                }
            }
            None
        }));
        self
    }

    /// Validates that the string contains only numeric ASCII digits.
    pub fn numeric(self) -> Self {
        self.numeric_msg("Character '{char}' is not a digit")
    }

    /// Validates that the string contains only numeric ASCII digits with a custom message template.
    pub fn numeric_msg(mut self, msg_template: &str) -> Self {
        let tpl = msg_template.to_string();
        self.rules.push(Arc::new(move |val| {
            for (idx, ch) in val.chars().enumerate() {
                if !ch.is_ascii_digit() {
                    let ch_str = ch.to_string();
                    let idx_str = idx.to_string();
                    let msg = format_template(
                        &tpl,
                        &[("char", &ch_str), ("index", &idx_str), ("value", val)],
                    );
                    return Some(ValidationError::new("numeric", msg));
                }
            }
            None
        }));
        self
    }

    /// Validates that the string has a valid email syntax without external dependencies.
    pub fn email(self) -> Self {
        self.email_msg("Invalid email format")
    }

    /// Validates that the string has a valid email syntax with a custom message.
    pub fn email_msg(mut self, msg: &str) -> Self {
        let err_msg = msg.to_string();
        self.rules.push(Arc::new(move |val| {
            let parts: Vec<&str> = val.split('@').collect();
            if parts.len() != 2 || parts[0].is_empty() || parts[1].is_empty() {
                return Some(ValidationError::new("email", err_msg.clone()));
            }

            let domain = parts[1];
            if !domain.contains('.') || domain.starts_with('.') || domain.ends_with('.') {
                return Some(ValidationError::new("email", err_msg.clone()));
            }

            if val.contains(' ') {
                return Some(ValidationError::new("email", err_msg.clone()));
            }

            None
        }));
        self
    }

    /// Enforces that the string starts with the given prefix.
    pub fn starts_with(self, prefix: &str) -> Self {
        self.starts_with_msg(prefix, "Must start with '{prefix}'")
    }

    /// Enforces that the string starts with the given prefix with a custom message template.
    pub fn starts_with_msg(mut self, prefix: &str, msg_template: &str) -> Self {
        let prefix = prefix.to_string();
        let tpl = msg_template.to_string();
        self.rules.push(Arc::new(move |val| {
            if !val.starts_with(&prefix) {
                let msg = format_template(&tpl, &[("prefix", &prefix), ("value", val)]);
                Some(ValidationError::new("starts_with", msg))
            } else {
                None
            }
        }));
        self
    }

    /// Enforces that the string ends with the given suffix.
    pub fn ends_with(self, suffix: &str) -> Self {
        self.ends_with_msg(suffix, "Must end with '{suffix}'")
    }

    /// Enforces that the string ends with the given suffix with a custom message template.
    pub fn ends_with_msg(mut self, suffix: &str, msg_template: &str) -> Self {
        let suffix = suffix.to_string();
        let tpl = msg_template.to_string();
        self.rules.push(Arc::new(move |val| {
            if !val.ends_with(&suffix) {
                let msg = format_template(&tpl, &[("suffix", &suffix), ("value", val)]);
                Some(ValidationError::new("ends_with", msg))
            } else {
                None
            }
        }));
        self
    }

    /// Enforces that the string contains a given substring.
    pub fn contains(self, substring: &str) -> Self {
        self.contains_msg(substring, "Must contain '{expected}'")
    }

    /// Enforces that the string contains a given substring with a custom message template.
    pub fn contains_msg(mut self, substring: &str, msg_template: &str) -> Self {
        let sub = substring.to_string();
        let tpl = msg_template.to_string();
        self.rules.push(Arc::new(move |val| {
            if !val.contains(&sub) {
                let msg = format_template(&tpl, &[("expected", &sub), ("value", val)]);
                Some(ValidationError::new("contains", msg))
            } else {
                None
            }
        }));
        self
    }

    /// Enforces that the string matches one of the allowed values.
    pub fn in_list(self, allowed: &[&str]) -> Self {
        self.in_list_msg(allowed, "Value '{value}' is not among allowed options")
    }

    /// Enforces that the string matches one of the allowed values with a custom message template.
    pub fn in_list_msg(mut self, allowed: &[&str], msg_template: &str) -> Self {
        let allowed_set: HashSet<String> = allowed.iter().map(|s| s.to_string()).collect();
        let tpl = msg_template.to_string();
        self.rules.push(Arc::new(move |val| {
            if !allowed_set.contains(val) {
                let msg = format_template(&tpl, &[("value", val)]);
                Some(ValidationError::new("in_list", msg))
            } else {
                None
            }
        }));
        self
    }

    /// Validates that the string is a valid web URL (starts with http:// or https:// and has a host).
    pub fn url(self) -> Self {
        self.url_msg("Must be a valid URL")
    }

    /// Validates that the string is a valid web URL with a custom message.
    pub fn url_msg(mut self, msg: &str) -> Self {
        let err_msg = msg.to_string();
        self.rules.push(Arc::new(move |val| {
            let is_valid = (val.starts_with("http://") && val.len() > 7)
                || (val.starts_with("https://") && val.len() > 8);
            if !is_valid || val.contains(' ') {
                Some(ValidationError::new("url", err_msg.clone()))
            } else {
                None
            }
        }));
        self
    }

    /// Validates that the string is a standard UUID (8-4-4-4-12 hex characters).
    pub fn uuid(self) -> Self {
        self.uuid_msg("Must be a valid UUID")
    }

    /// Validates that the string is a standard UUID with a custom message.
    pub fn uuid_msg(mut self, msg: &str) -> Self {
        let err_msg = msg.to_string();
        self.rules.push(Arc::new(move |val| {
            let is_valid = if val.len() == 36 {
                val.chars().enumerate().all(|(idx, ch)| {
                    if idx == 8 || idx == 13 || idx == 18 || idx == 23 {
                        ch == '-'
                    } else {
                        ch.is_ascii_hexdigit()
                    }
                })
            } else {
                false
            };

            if !is_valid {
                Some(ValidationError::new("uuid", err_msg.clone()))
            } else {
                None
            }
        }));
        self
    }

    /// Validates that the string is a valid IPv4 or IPv6 address.
    pub fn ip(self) -> Self {
        self.ip_msg("Must be a valid IP address")
    }

    /// Validates that the string is a valid IPv4 or IPv6 address with a custom message.
    pub fn ip_msg(mut self, msg: &str) -> Self {
        let err_msg = msg.to_string();
        self.rules.push(Arc::new(move |val| {
            if val.parse::<IpAddr>().is_err() {
                Some(ValidationError::new("ip", err_msg.clone()))
            } else {
                None
            }
        }));
        self
    }

    /// Adds a custom user-defined validation closure.
    pub fn custom<F>(mut self, validator: F) -> Self
    where
        F: Fn(&str) -> Result<(), ValidationError> + Send + Sync + 'static,
    {
        self.rules.push(Arc::new(move |val| validator(val).err()));
        self
    }

    #[cfg(feature = "regex")]
    /// Validates the string against a regex pattern.
    pub fn regex(self, pattern: &str) -> Self {
        self.regex_msg(pattern, "Value does not match required pattern '{pattern}'")
    }

    #[cfg(feature = "regex")]
    /// Validates the string against a regex pattern with a custom message template.
    ///
    /// Available placeholders: `{pattern}`, `{value}`.
    pub fn regex_msg(mut self, pattern: &str, msg_template: &str) -> Self {
        let tpl = msg_template.to_string();
        match regex::Regex::new(pattern) {
            Ok(re) => {
                let pat_str = pattern.to_string();
                self.rules.push(Arc::new(move |val| {
                    if !re.is_match(val) {
                        let msg = format_template(&tpl, &[("pattern", &pat_str), ("value", val)]);
                        Some(ValidationError::new("regex", msg))
                    } else {
                        None
                    }
                }));
            }
            Err(e) => {
                let err_msg = format!("Invalid regular expression '{}': {}", pattern, e);
                self.rules.push(Arc::new(move |_| {
                    Some(ValidationError::new(
                        "invalid_regex_pattern",
                        err_msg.clone(),
                    ))
                }));
            }
        }
        self
    }
}

impl Validator<str> for StringValidator {
    fn validate_all(&self, value: &str) -> Vec<ValidationError> {
        let mut errors = Vec::new();
        for rule in &self.rules {
            if let Some(err) = rule(value) {
                errors.push(err);
            }
        }
        errors
    }
}

impl Validator<String> for StringValidator {
    fn validate_all(&self, value: &String) -> Vec<ValidationError> {
        self.validate_all(value.as_str())
    }
}

impl Validator<&str> for StringValidator {
    fn validate_all(&self, value: &&str) -> Vec<ValidationError> {
        self.validate_all(*value)
    }
}