All posts

How to Fix Validation Error in Rust

Fix Validation Error in your Rust app. Understand the root cause and apply the right solution.

Validation Errors in Rust

Rust validation errors typically come from the validator crate or manual validation logic. Rust's type system handles many cases, but business rule validation still needs explicit checks.

Why It Happens

  • Struct fields pass type checks but fail range or format validation
  • Deserialized data from JSON/forms violating business rules
  • Custom validation logic returning errors

How to Fix

Use the validator crate with derive macros:

use validator::{Validate, ValidationError};
use serde::Deserialize;

#[derive(Debug, Deserialize, Validate)]
pub struct CreateUser {
    #[validate(length(min = 1, max = 100))]
    pub name: String,

    #[validate(email)]
    pub email: String,

    #[validate(range(min = 1, max = 150))]
    pub age: u8,

    #[validate(custom(function = "validate_username"))]
    pub username: String,
}

fn validate_username(username: &str) -> Result<(), ValidationError> {
    if username.contains(' ') {
        return Err(ValidationError::new("no_spaces"));
    }
    Ok(())
}

pub fn handle_create(data: CreateUser) -> Result<(), Vec<String>> {
    data.validate().map_err(|e| {
        e.field_errors().iter()
            .flat_map(|(field, errs)| {
                errs.iter().map(move |e| format!("{}: {}", field, e.code))
            })
            .collect()
    })
}

Validate at the boundary — deserialize first, then validate, then pass clean data to your domain logic.

Bugsly for Rust

Bugsly captures validation errors as structured events with field names and constraint violations, plus the raw input that triggered them, making it easy to fix API contract issues.

Try Bugsly Free

AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.

Get Started Free