Universal Data Validator (Rust)
A comprehensive data validation library for Rust that works across API, database, and form contexts.
Features
- ✅ Rich Validator Types: String, integer, float, bool, email, URL, UUID, date, datetime, numeric, not-empty, enum, one-of, array (
Vec) and object (Map) - ✅ Schema-Based Validation: Define complex, nested data structures
- ✅ Custom Validators: Add your own validation logic
- ✅ Nullable & Optional: Fine-grained control over missing and
nullvalues - ✅ Strict Mode: Reject unknown fields
- ✅ Fail-fast Mode: Stop at the first validation error
- ✅ Sensitive Fields: Redact secrets from error messages and error values
- ✅ Clear Error Messages: Detailed error reporting with full field paths
- ✅ Production Ready: Comprehensive test coverage
Installation
Add this to your Cargo.toml:
[]
= "1.0"
= "1.0"
Quick Start
use json;
use ;
Usage Examples
String Validation
use validators;
use Regex;
// Basic string
let validator = string;
// String with length constraints
let username_validator = string.min.max;
// String with a pre-compiled regex pattern
let phone_validator = string.pattern;
// String with a fallible pattern compile
let pattern_validator = string.try_pattern.unwrap;
// String with choices
let theme_validator = string.choices;
// Optional and nullable string
let bio_validator = string.optional.nullable;
Integer Validation
use validators;
// Integer with range
let age_validator = int.min.max;
// Optional integer
let score_validator = int.optional;
// Reject floats like 1.5
let result = age_validator.validate;
assert!;
Float Validation
use validators;
let score_validator = float.min.max;
Boolean Validation
use validators;
let active_validator = bool;
Email and URL Validation
use validators;
let email_validator = email;
let url_validator = url;
Format, Membership, and Union Validation
use json;
use validators;
use Regex;
// Fixed-format string validators
let id_validator = uuid;
let date_validator = date; // YYYY-MM-DD
let ts_validator = datetime; // ISO-8601 style
let numeric_validator = numeric; // string containing a number
// Non-empty string, array, or object
let required_body = not_empty;
// Enum membership over arbitrary JSON values (deep equality).
// Named `enum_values` because `enum` is a Rust keyword; `validators::r#enum`
// is available as an alias.
let enum_validator = enum_values;
// Union: valid when at least one branch produces zero errors
let union_validator = one_of;
// String validator anchored to a caller-supplied regex
let pattern_validator = regex;
Array and Object Validation
use validators;
use json;
// Array of integers
let tags_validator = vec
.item
.min
.max;
// Nested object
let user_validator = map
.field
.field;
let data = json!;
assert!;
Schema Validation
use json;
use ;
let schema = new
.field
.field
.field
.field
.field
.field
.strict;
let data = json!;
let result = schema.validate;
if result.is_valid else
Strict Mode
When strict mode is enabled, keys present in the input but not in the schema produce an Unknown field error.
use json;
use ;
let schema = new
.field
.strict;
let result = schema.validate;
assert!;
assert_eq!;
assert_eq!;
Fail-fast Mode
When fail-fast mode is enabled, validation stops at the first error and returns a ValidationResult containing exactly one error. Set .fail_fast(true) on a Schema, MapValidator, VecValidator, or any leaf validator. The flag is propagated to nested validators, so enabling it on a parent also applies to children.
use json;
use ;
let schema = new
.fail_fast
.field
.field;
let result = schema.validate;
assert!;
assert_eq!;
Because HashMap iteration order is not deterministic, which error is returned first may vary; only the count (1) is guaranteed.
Sensitive Fields
Mark fields that may contain secrets (passwords, tokens) with
.sensitive(true). Every error a sensitive validator produces redacts the
offending value: message interpolations render as *** and
ValidationError::value is None, so errors can be logged safely. Messages
that never embed the input (length/bounds, Field is required,
Unknown field) are unchanged.
The flag is per-validator and is not inherited by nested validators — mark each sensitive field explicitly.
use json;
use validators;
let validator = email.sensitive;
let result = validator.validate;
assert_eq!;
assert!;
Pattern Security Notes
- Input length cap: before running any
patterncheck (including the fixed email/URL/UUID/date/datetime/numeric patterns), inputs longer thanMAX_PATTERN_INPUT_LENGTH(10,000 characters) skip the match and produce the normal pattern error. Rust'sregexcrate guarantees linear-time matching, so this is not strictly needed here — the cap exists for cross-language parity with backtracking engines (Pythonre, JSRegExp). - Trusted patterns only:
patternis executed with the platform regex engine; in other runtimes a hostile pattern can cause exponential backtracking. Schemas should come from trusted sources. - Email/URL are sanity checks only: the email pattern does not enforce
RFC 5321 length limits and cannot prove deliverability; the URL pattern
performs no IDN/port validation and accepts
http://x..
Custom Validators
Add ad-hoc validation with .custom():
use json;
use validators;
let even_validator = int.custom;
assert!;
assert!;
Error Handling
use json;
use ;
let schema = new.field;
let result = schema.validate;
if !result.is_valid
API Reference
All validators and Schema support .fail_fast(true): validation stops at the first error and the flag is propagated to nested children.
All validators also support .sensitive(bool): redact the offending value from error messages (***) and leave ValidationError::value as None. Per-validator; not inherited by nested validators.
Validators
-
validators::string()- String validator.min(n)- Minimum Unicode length.max(n)- Maximum Unicode length.pattern(Regex)- Pre-compiled regex pattern (infallible).try_pattern(&str)- Compile a regex, returnsResult<Self, regex::Error>.choices(Vec<String>)- Allowed values.optional()- Make field optional.nullable()- Allow explicitnull.custom(...)- Add custom validator
-
validators::int()- Integer validator.min(n)- Minimum value.max(n)- Maximum value.optional(),.nullable(),.custom(...)
-
validators::float()- Number validator (accepts any JSON number).min(n),.max(n),.optional(),.nullable(),.custom(...)
-
validators::bool()- Boolean validator.optional(),.nullable(),.custom(...)
-
validators::email()- Email validator.optional(),.nullable(),.custom(...)
-
validators::url()- URL validator.optional(),.nullable(),.custom(...)
-
validators::uuid()- UUID string validator.optional(),.nullable(),.custom(...)
-
validators::date()-YYYY-MM-DDdate string validator.optional(),.nullable(),.custom(...)
-
validators::datetime()- ISO-8601 style datetime string validator.optional(),.nullable(),.custom(...)
-
validators::numeric()- Numeric string validator.optional(),.nullable(),.custom(...)
-
validators::not_empty()- Requires a non-empty string, array, or object.optional(),.nullable(),.custom(...)
-
validators::enum_values(Vec<Value>)/validators::r#enum(...)- Membership in a set of JSON values.optional(),.nullable(),.custom(...)
-
validators::one_of(Vec<Box<dyn Validator>>)- Accepts the value if any branch validates cleanly.optional(),.nullable(),.custom(...)
-
validators::regex(Regex)- String validator anchored to a caller-supplied pattern.optional(),.nullable(),.custom(...)
-
validators::vec()/validators::list()- Array validator.item(validator)- Validator for each item.min(n)/.max(n)- Array length bounds.fail_fast(bool)- Stop at the first item error.optional(),.nullable(),.custom(...)
-
validators::map()/validators::dict()- Object validator.field(name, validator)- Add a child field.schema(HashMap<...>)- Replace the whole schema.strict(bool)- Reject unknown keys.fail_fast(bool)- Stop at the first field error.optional(),.nullable(),.custom(...)
Schema
Schema::new()- Create a new schema.field(name, validator)- Add a top-level field validator.strict(bool)- Enable strict mode.fail_fast(bool)- Stop at the first validation error.validate(data)- Validate aserde_json::Valueobject.validate_or_raise(data)- ReturnsOk(())orErr(ValidationResult).try_validate(data)- ReturnsOk(())orErr(ValidationErrors), an error aggregate implementingstd::error::Error(onefield: messageper line)
ValidationResult
.is_valid()- Check if validation passed.errors()- Get a slice of validation errors.into_result()- Convert toOk(())orErr(ValidationErrors)
ValidationError
.field- Field path that failed validation.code- Machine-readable error code (e.g.required,type,email).message- Error message.value- Optionalserde_json::Valuethat failed validation
Error Paths
Error field values follow a fixed JSONPath-ish format: object fields are
joined with . (user.address.city) and array indices are appended in
brackets (tags[0], users[1].email). A type error on a top-level
(non-object) schema input uses the field name root.
No Coercion / Transform
By design, validators never mutate or normalize input. Trimming, case-folding, and parsing strings into numbers or dates are the caller's responsibility before validation.
Testing
# Run tests
# Run tests with output
# Build
License
MIT License
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Changelog
1.0.0 (2024-01-15)
- Initial release
- Support for string, int, email, URL validators
- Schema-based validation
- Comprehensive test coverage