Skip to main content

universal_validator/
lib.rs

1//! Universal Data Validator
2//!
3//! A comprehensive data validation library for Rust that works across API, database, and form contexts.
4//!
5//! # Features
6//!
7//! - **Rich Validator Types**: String, i32, i64, f64, bool, email, URL, Vec, HashMap
8//! - **Schema-Based Validation**: Define complex data structures
9//! - **Custom Validators**: Add your own validation logic
10//! - **Nested Validation**: Validate nested objects and vectors
11//! - **Clear Error Messages**: Detailed error reporting with field paths
12//!
13//! # Examples
14//!
15//! ```
16//! use universal_validator::{Schema, Validator, validators};
17//!
18//! let schema = Schema::new()
19//!     .field("email", validators::email())
20//!     .field("age", validators::int().min(0).max(120));
21//!
22//! let mut data = std::collections::HashMap::new();
23//! data.insert("email".to_string(), "user@example.com".to_string());
24//! data.insert("age".to_string(), "25".to_string());
25//!
26//! let result = schema.validate(&data);
27//! assert!(result.is_valid());
28//! ```
29
30use regex::Regex;
31use std::collections::HashMap;
32use std::fmt;
33
34/// Validation error
35#[derive(Debug, Clone)]
36pub struct ValidationError {
37    pub field: String,
38    pub message: String,
39    pub value: Option<String>,
40}
41
42impl ValidationError {
43    pub fn new(field: impl Into<String>, message: impl Into<String>) -> Self {
44        Self {
45            field: field.into(),
46            message: message.into(),
47            value: None,
48        }
49    }
50
51    pub fn with_value(mut self, value: impl Into<String>) -> Self {
52        self.value = Some(value.into());
53        self
54    }
55}
56
57impl fmt::Display for ValidationError {
58    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59        write!(f, "{}: {}", self.field, self.message)
60    }
61}
62
63impl std::error::Error for ValidationError {}
64
65/// Validation result
66#[derive(Debug)]
67pub struct ValidationResult {
68    errors: Vec<ValidationError>,
69}
70
71impl ValidationResult {
72    pub fn new() -> Self {
73        Self { errors: Vec::new() }
74    }
75
76    pub fn is_valid(&self) -> bool {
77        self.errors.is_empty()
78    }
79
80    pub fn errors(&self) -> &[ValidationError] {
81        &self.errors
82    }
83
84    pub fn add_error(&mut self, error: ValidationError) {
85        self.errors.push(error);
86    }
87
88    pub fn merge(&mut self, other: ValidationResult) {
89        self.errors.extend(other.errors);
90    }
91}
92
93impl Default for ValidationResult {
94    fn default() -> Self {
95        Self::new()
96    }
97}
98
99/// Validator trait
100pub trait Validator: Send + Sync {
101    fn validate(&self, value: &str, field: &str) -> ValidationResult;
102    fn is_required(&self) -> bool {
103        true
104    }
105}
106
107/// String validator
108pub struct StringValidator {
109    min_length: Option<usize>,
110    max_length: Option<usize>,
111    pattern: Option<Regex>,
112    choices: Option<Vec<String>>,
113    required: bool,
114}
115
116impl StringValidator {
117    pub fn new() -> Self {
118        Self {
119            min_length: None,
120            max_length: None,
121            pattern: None,
122            choices: None,
123            required: true,
124        }
125    }
126
127    pub fn min(mut self, min: usize) -> Self {
128        self.min_length = Some(min);
129        self
130    }
131
132    pub fn max(mut self, max: usize) -> Self {
133        self.max_length = Some(max);
134        self
135    }
136
137    pub fn pattern(mut self, pattern: &str) -> Self {
138        self.pattern = Some(Regex::new(pattern).expect("Invalid regex pattern"));
139        self
140    }
141
142    pub fn choices(mut self, choices: Vec<String>) -> Self {
143        self.choices = Some(choices);
144        self
145    }
146
147    pub fn optional(mut self) -> Self {
148        self.required = false;
149        self
150    }
151}
152
153impl Validator for StringValidator {
154    fn validate(&self, value: &str, field: &str) -> ValidationResult {
155        let mut result = ValidationResult::new();
156
157        if let Some(min) = self.min_length {
158            if value.len() < min {
159                result.add_error(
160                    ValidationError::new(
161                        field,
162                        format!("String length must be at least {}, got {}", min, value.len()),
163                    )
164                    .with_value(value),
165                );
166            }
167        }
168
169        if let Some(max) = self.max_length {
170            if value.len() > max {
171                result.add_error(
172                    ValidationError::new(
173                        field,
174                        format!("String length must be at most {}, got {}", max, value.len()),
175                    )
176                    .with_value(value),
177                );
178            }
179        }
180
181        if let Some(pattern) = &self.pattern {
182            if !pattern.is_match(value) {
183                result.add_error(
184                    ValidationError::new(field, format!("String does not match pattern {}", pattern))
185                        .with_value(value),
186                );
187            }
188        }
189
190        if let Some(choices) = &self.choices {
191            if !choices.contains(&value.to_string()) {
192                result.add_error(
193                    ValidationError::new(
194                        field,
195                        format!("Value must be one of {:?}, got '{}'", choices, value),
196                    )
197                    .with_value(value),
198                );
199            }
200        }
201
202        result
203    }
204
205    fn is_required(&self) -> bool {
206        self.required
207    }
208}
209
210/// Integer validator
211pub struct IntValidator {
212    min_value: Option<i64>,
213    max_value: Option<i64>,
214    required: bool,
215}
216
217impl IntValidator {
218    pub fn new() -> Self {
219        Self {
220            min_value: None,
221            max_value: None,
222            required: true,
223        }
224    }
225
226    pub fn min(mut self, min: i64) -> Self {
227        self.min_value = Some(min);
228        self
229    }
230
231    pub fn max(mut self, max: i64) -> Self {
232        self.max_value = Some(max);
233        self
234    }
235
236    pub fn optional(mut self) -> Self {
237        self.required = false;
238        self
239    }
240}
241
242impl Validator for IntValidator {
243    fn validate(&self, value: &str, field: &str) -> ValidationResult {
244        let mut result = ValidationResult::new();
245
246        let num = match value.parse::<i64>() {
247            Ok(n) => n,
248            Err(_) => {
249                result.add_error(
250                    ValidationError::new(field, format!("Expected integer, got '{}'", value))
251                        .with_value(value),
252                );
253                return result;
254            }
255        };
256
257        if let Some(min) = self.min_value {
258            if num < min {
259                result.add_error(
260                    ValidationError::new(field, format!("Value must be at least {}, got {}", min, num))
261                        .with_value(value),
262                );
263            }
264        }
265
266        if let Some(max) = self.max_value {
267            if num > max {
268                result.add_error(
269                    ValidationError::new(field, format!("Value must be at most {}, got {}", max, num))
270                        .with_value(value),
271                );
272            }
273        }
274
275        result
276    }
277
278    fn is_required(&self) -> bool {
279        self.required
280    }
281}
282
283/// Email validator
284pub struct EmailValidator {
285    required: bool,
286}
287
288impl EmailValidator {
289    pub fn new() -> Self {
290        Self { required: true }
291    }
292
293    pub fn optional(mut self) -> Self {
294        self.required = false;
295        self
296    }
297}
298
299impl Validator for EmailValidator {
300    fn validate(&self, value: &str, field: &str) -> ValidationResult {
301        let mut result = ValidationResult::new();
302        let email_pattern = Regex::new(r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$").unwrap();
303
304        if !email_pattern.is_match(value) {
305            result.add_error(
306                ValidationError::new(field, format!("Invalid email address: {}", value))
307                    .with_value(value),
308            );
309        }
310
311        result
312    }
313
314    fn is_required(&self) -> bool {
315        self.required
316    }
317}
318
319/// URL validator
320pub struct UrlValidator {
321    required: bool,
322}
323
324impl UrlValidator {
325    pub fn new() -> Self {
326        Self { required: true }
327    }
328
329    pub fn optional(mut self) -> Self {
330        self.required = false;
331        self
332    }
333}
334
335impl Validator for UrlValidator {
336    fn validate(&self, value: &str, field: &str) -> ValidationResult {
337        let mut result = ValidationResult::new();
338        let url_pattern = Regex::new(r"^https?://[^\s/$.?#].[^\s]*$").unwrap();
339
340        if !url_pattern.is_match(value) {
341            result.add_error(
342                ValidationError::new(field, format!("Invalid URL: {}", value)).with_value(value),
343            );
344        }
345
346        result
347    }
348
349    fn is_required(&self) -> bool {
350        self.required
351    }
352}
353
354/// Schema for validating complex data structures
355pub struct Schema {
356    fields: HashMap<String, Box<dyn Validator>>,
357}
358
359impl Schema {
360    pub fn new() -> Self {
361        Self {
362            fields: HashMap::new(),
363        }
364    }
365
366    pub fn field(mut self, name: impl Into<String>, validator: impl Validator + 'static) -> Self {
367        self.fields.insert(name.into(), Box::new(validator));
368        self
369    }
370
371    pub fn validate(&self, data: &HashMap<String, String>) -> ValidationResult {
372        let mut result = ValidationResult::new();
373
374        for (field, validator) in &self.fields {
375            if let Some(value) = data.get(field) {
376                let field_result = validator.validate(value, field);
377                result.merge(field_result);
378            } else if validator.is_required() {
379                result.add_error(ValidationError::new(field, "Field is required"));
380            }
381        }
382
383        result
384    }
385}
386
387impl Default for Schema {
388    fn default() -> Self {
389        Self::new()
390    }
391}
392
393/// Validator factory functions
394pub mod validators {
395    use super::*;
396
397    pub fn string() -> StringValidator {
398        StringValidator::new()
399    }
400
401    pub fn int() -> IntValidator {
402        IntValidator::new()
403    }
404
405    pub fn email() -> EmailValidator {
406        EmailValidator::new()
407    }
408
409    pub fn url() -> UrlValidator {
410        UrlValidator::new()
411    }
412}
413
414#[cfg(test)]
415mod tests {
416    use super::*;
417
418    #[test]
419    fn test_string_validator() {
420        let validator = validators::string().min(3).max(10);
421        
422        let result = validator.validate("hello", "name");
423        assert!(result.is_valid());
424
425        let result = validator.validate("ab", "name");
426        assert!(!result.is_valid());
427
428        let result = validator.validate("hello world", "name");
429        assert!(!result.is_valid());
430    }
431
432    #[test]
433    fn test_int_validator() {
434        let validator = validators::int().min(0).max(120);
435
436        let result = validator.validate("25", "age");
437        assert!(result.is_valid());
438
439        let result = validator.validate("-1", "age");
440        assert!(!result.is_valid());
441
442        let result = validator.validate("150", "age");
443        assert!(!result.is_valid());
444
445        let result = validator.validate("not_a_number", "age");
446        assert!(!result.is_valid());
447    }
448
449    #[test]
450    fn test_email_validator() {
451        let validator = validators::email();
452
453        let result = validator.validate("user@example.com", "email");
454        assert!(result.is_valid());
455
456        let result = validator.validate("invalid-email", "email");
457        assert!(!result.is_valid());
458    }
459
460    #[test]
461    fn test_url_validator() {
462        let validator = validators::url();
463
464        let result = validator.validate("https://example.com", "url");
465        assert!(result.is_valid());
466
467        let result = validator.validate("not-a-url", "url");
468        assert!(!result.is_valid());
469    }
470
471    #[test]
472    fn test_schema() {
473        let schema = Schema::new()
474            .field("username", validators::string().min(3).max(20))
475            .field("email", validators::email())
476            .field("age", validators::int().min(0).max(120));
477
478        let mut data = HashMap::new();
479        data.insert("username".to_string(), "john_doe".to_string());
480        data.insert("email".to_string(), "john@example.com".to_string());
481        data.insert("age".to_string(), "25".to_string());
482
483        let result = schema.validate(&data);
484        assert!(result.is_valid());
485    }
486
487    #[test]
488    fn test_schema_invalid() {
489        let schema = Schema::new()
490            .field("username", validators::string().min(3))
491            .field("email", validators::email());
492
493        let mut data = HashMap::new();
494        data.insert("username".to_string(), "ab".to_string());
495        data.insert("email".to_string(), "invalid".to_string());
496
497        let result = schema.validate(&data);
498        assert!(!result.is_valid());
499        assert_eq!(result.errors().len(), 2);
500    }
501
502    #[test]
503    fn test_schema_missing_required() {
504        let schema = Schema::new()
505            .field("username", validators::string())
506            .field("email", validators::email());
507
508        let data = HashMap::new();
509
510        let result = schema.validate(&data);
511        assert!(!result.is_valid());
512        assert_eq!(result.errors().len(), 2);
513    }
514
515    #[test]
516    fn test_optional_field() {
517        let schema = Schema::new()
518            .field("username", validators::string())
519            .field("bio", validators::string().optional());
520
521        let mut data = HashMap::new();
522        data.insert("username".to_string(), "john_doe".to_string());
523
524        let result = schema.validate(&data);
525        assert!(result.is_valid());
526    }
527}