Derive Macro Validate

Source
#[derive(Validate)]
Expand description

Procedural macro to automatically implement the Validate trait for structs.

This macro generates an implementation of the Validate trait for the annotated struct. It iterates over each named field in the struct, invokes the validate method on each field, prefixes any resulting ValidationError with the field name, and collects all errors into a single Vec<ValidationError>.

§Constraints

  • The macro can only be derived for structs with named fields.
  • Each field in the struct must implement the Validate trait.

§Examples

use struct_validation_core::{Validate, ValidationError, validate};
use struct_validation_derive::Validate;

struct NonEmptyString(String);
 
impl Validate for NonEmptyString {
    fn validate(&self) -> Vec<ValidationError> {
        let mut errors = Vec::new();
        if self.0.is_empty() {
            errors.push(ValidationError::new("String", "must not be empty"));
        }
        errors
    }
}
impl From<String> for NonEmptyString {
    fn from(value: String) -> Self {
       Self(value)
    }
}
 
#[derive(Validate)]
struct User {
    username: NonEmptyString,
    email: NonEmptyString,
}


fn main() {
    let user = User {
        username: "".to_string().into(),
        email: "invalidemail.com".to_string().into(),
    };

    let errors = user.validate();

    for error in errors {
        println!("Error in {}: {}", error.field, error.message);
    }
}

Output:

Error in username: must not be empty
Error in email: must not be empty