Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Validation of nested structs fails if there are validation errors at both levels of nesting #363

Open
BobWall23 opened this issue Jan 2, 2025 · 1 comment

Comments

@BobWall23
Copy link

When validating a structure with a nested structure, if there are validation errors in the nested struct and in the containing struct, using a custom validation function, library panics with

thread 'test::test_no_primary_entry' panicked at /Users/bob/.cargo/registry/src/index.crates.io-6f17d22bba15001f/validator-0.19.0/src/types.rs:185:13:
Attempt to replace non-empty ValidationErrors entry

This is using v0.19

Test case:

use validator::{Validate, ValidationError};
use regex::Regex;
use lazy_static::lazy_static;
use serde::Serialize;


lazy_static! {
    pub static ref VALID_FIELD_RE: Regex = Regex::new(r"^[a-z0-9A-Z_-]+$").unwrap();
}

#[derive(Validate, Serialize)]
struct Entry {
    #[validate(regex(path = *VALID_FIELD_RE))]
    field1: String,
    primary: bool
}

#[derive(Validate, Serialize)]
struct Entries {
    #[validate(nested)]
    #[validate(custom(function="validate_entries"))]
    entries: Option<Vec<Entry>>
}

fn validate_entries(entries: &[Entry]) -> Result<(), ValidationError> {
    let primary_count = entries.iter().filter(|entry| entry.primary).count();
    if primary_count != 1 {
        Err(ValidationError::new(
            "There must be exactly one primary entry.",
        ))
    } else {
        Ok(())
    }
}

fn main() {
    println!("Hello, world!");
}

#[cfg(test)]
pub(crate) mod test {
    use super::*;

    #[test]
    fn test_no_primary_entry() {
        let error = Entries {
            entries: Some(vec!(Entry { field1: "abc#012".to_string(), primary: false }))
        }
        .validate()
        .unwrap_err();
        assert_eq!(error.errors().len(), 1);
    }
}

Cargo.toml:

[package]
name = "validator"
version = "0.1.0"
edition = "2021"

[dependencies]
lazy_static = "1.5"
regex = "1"
serde = { version = "1", features = ["derive"] }
validator = { version = "0.19", features = ["derive"] }
@Keats
Copy link
Owner

Keats commented Jan 3, 2025

It has been fixed in #359 it just needs to be released

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants