Hello, I am trying to validate structs using rust - validator crate's custom function. I was able to follow docs and everything works well unless I had a requirement to validate child vec field "date" based on the parent's field "date_format" so I had to pass the args to custom function. I guess there are special treatment needed to validate vector with custom function and args.
Here are structs:
#[derive(Serialize, Clone, Deserialize, Debug)]
pub struct ParentArg {
pub model: Parent
}
#[derive(Serialize, Clone, Deserialize, Debug, Validate)]
#[validate(context = ParentArg)]
pub struct Parent {
#[validate(required(message = "REQUIRED_FIELD"))]
pub date_format: Option<String>,
#[validate(nested)]
#[validate(length(min = 1, message = "REQUIRED_FIELD"))]
pub data: Option<Vec<Child>>,
//---- other fields
}
#[derive(Serialize, Clone, Deserialize, Debug, Validate)]
#[validate(context = ParentArg)]
pub struct Child {
#[validate(required(message = "REQUIRED_FIELD"))]
pub key: Option<String>,
#[validate(
custom(
function = validate_date,
use_context
)
)]
pub date: Option<String>.
//---- some other fields to validate
}
// Custom function
fn validate_date(
field: &str,
arg: &ParentArg
) -> Result<(), ValidationError> {
let date_format = &arg.model.date_format.unwrap();
if NaiveDate::parse_from_str(field, date_format).is_ok() {
return Ok(());
}
Err(ValidationError::new("INVALID_DATE"))
}
// Calling the validate_with_args
body: web::Json<Parent>
let arg = ParentArg {
model: body.clone()
};
let is_valid = &body.validate_with_args(&arg);
Error:
the method `validate` exists for reference `&&Vec<Child>`, but its trait bounds were not satisfied
the following trait bounds were not satisfied:
`Vec<Child>: Validate`
which is required by `&Vec<Child>: Validate`
`&Vec<Child>: Validate`
which is required by `&&Vec<Child>: Validate`
`Child: Validate`
which is required by `Vec<Child>: Validate`
`Child: Validate`
which is required by `[Child]: Validate`