From where Nesting ( Struct and/or List ) comes from ?
Closed this issue ยท 2 comments
HosMercury commented
Hi! I'm a bit confused about the ValidationErrorKind
whereas Field
type is easy to understand. Can you explain how/from where Struct
or List
might be added to the mix? is there any default insertion from the crate? or are they added by me?
Also, could you review my recursive function for extracting all errors? Here's my implementation: bc I do not have any nesting right now
pub fn validation_errs(e: ValidationErrors) -> HashMap<String, ValidationError> {
let mut errors: HashMap<String, ValidationError> = HashMap::new();
e.errors().iter().for_each(|(field_name, error_kind)| match error_kind {
ValidationErrorsKind::Field(error_messages) => {
error_messages.iter().for_each(|error| {
errors.insert(field_name.to_string(), error.clone());
})
}
ValidationErrorsKind::Struct(errors) => validation_errs(*errors.clone()),
ValidationErrorsKind::List(errors) => errors.clone().iter().for_each(|(_, errors)| validation_errs(*errors.clone())),
});
errors
}
Any suggestions you have would be greatly appreciated. Thank you
Keats commented
You can have nested errors from a struct or from a list. See this example from the README and look at the SignupData:
use serde::Deserialize;
// A trait that the Validate derive will impl
use validator::Validate;
#[derive(Debug, Validate, Deserialize)]
struct SignupData {
#[validate]
contact_details: ContactDetails,
#[validate]
preferences: Vec<Preference>,
#[validate(required)]
allow_cookies: Option<bool>,
}
#[derive(Debug, Validate, Deserialize)]
struct ContactDetails {
#[validate(email)]
mail: String,
#[validate(phone)]
phone: String
}
#[derive(Debug, Validate, Deserialize)]
struct Preference {
#[validate(length(min = 4))]
name: String,
value: bool,
}
match signup_data.validate() {
Ok(_) => (),
Err(e) => return e;
};
You can have an error in contact_details or in any Preference
in the list
HosMercury commented
Ty very much