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.

RustForm 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
}

How it works

Count the function validate as the entire surface area of Rust Form Validation with Serde.

Points of care

  • Plan for an install step: serde:: is a real dependency, resolved by the package manager.

Using it

Entry signature: fn validate(form: &LoginForm) -> Vec<ValidationError>

validate is what another module would consume; nothing else here is load-bearing for callers.

Key statements

errors.push(ValidationError { field: "password".into(), message: "Min 8 chars".into() });

Interactive Tools for This Topic

FAQ

Does this require external packages?
Yes — `serde::`. Add it to your project before running the snippet.