Rust Validator
How ValidationError
, ValidationErrorsKind
, and ValidationErrors
work together
-
ValidationError
: This represents a single validation error.pub struct ValidationError { pub code: Cow<'static, str>, pub message: Option<Cow<'static, str>>, pub params: HashMap<Cow<'static, str>, Value>, }
code
: A short identifier for the type of error.message
: An optional human-readable description.params
: Additional context or data about the error.
The
Display
implementation forValidationError
shows that:- If a
message
is provided, it’s used directly. - Otherwise, it falls back to displaying the
code
andparams
.
-
ValidationErrorsKind
: This enum represents different types of validation errors:pub enum ValidationErrorsKind { Field(Vec<ValidationError>), Struct(Box<ValidationErrors>), List(BTreeMap<usize, Box<ValidationErrors>>), }
Field
: For errors on a single field.Struct
: For errors in a nested struct.List
: For errors in a vector of nested structs.
-
ValidationErrors
: This is a collection of all errors found during validation.pub struct ValidationErrors(pub HashMap<&'static str, ValidationErrorsKind>);
It maps field names to their respective
ValidationErrorsKind
.
How they work together:
-
Field-level validation: When validating a single field, you create a
ValidationError
. If multiple errors occur on a field, they’re collected into aVec<ValidationError>
and stored asValidationErrorsKind::Field
. -
Struct-level validation: For a struct, you create a
ValidationErrors
instance. Each field’s errors are added to this instance, with the field name as the key and the appropriateValidationErrorsKind
as the value. -
Nested struct validation: When validating a nested struct, its errors are stored as
ValidationErrorsKind::Struct
, which contains a boxedValidationErrors
. -
List validation: For a vector of structs, errors are stored as h
ValidationErrorsKind::List
, mapping the index to a boxedValidationErrors
for each invalid item. -
Error Display: The
display_errors
function shows how these types work together to create a readable error message:-
It recursively traverses the error structure, building a path to show where each error
See also validator/src/display_impl.rs for more insights on how errors are displayed.
-