How to Validate Data in Rust (validator crate)

Use the validator crate with derive macros to define and enforce data rules on Rust structs.

Add the validator crate to your Cargo.toml and use the #[derive(Validate)] macro with field attributes to enforce rules at runtime.

[dependencies]
validator = { version = "0.19", features = ["derive"] }
use validator::Validate;

#[derive(Validate)]
struct User {
    #[validate(length(min = 3, message = "Username must be at least 3 characters"))]
    username: String,
    #[validate(email(message = "Invalid email address"))]
    email: String,
}

fn main() {
    let user = User {
        username: "ab".to_string(),
        email: "not-an-email".to_string(),
    };
    
    match user.validate() {
        Ok(_) => println!("Valid!"),
        Err(e) => println!("Validation failed: {:?}", e),
    }
}