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.
Code
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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- Does this require external packages?
- Yes — `serde::`. Add it to your project before running the snippet.
Report a problem with this exampleOpens a pre-filled issue on GitHub.