Rust Form Validation with Serde

Validate form data in Rust using serde Deserialize with custom validation, error collection, and JSON response generation. Includes nested struct validation.

Rust Form Validation

Code

snippet
use serde::{Deserialize, Serialize};

#[derive(Deserialize)]
struct LoginForm {
    email: String,
    password: String,
}

#[derive(Serialize)]
struct ValidationError {
    field: String,
    message: String,
}

fn validate(form: &LoginForm) -> Vec<ValidationError> {
    let mut errors = vec![];
    if !form.email.contains('@') {
        errors.push(ValidationError { field: "email".into(), message: "Invalid email".into() });
    }
    if form.password.len() < 8 {
        errors.push(ValidationError { field: "password".into(), message: "Min 8 chars".into() });
    }
    errors
}