validator — Data Validation in Rust

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

What is validator?

validator is a popular library for data validation in Rust. It provides flexible and expressive tools for checking the correctness of input data: strings, numbers, email addresses, URLs, IP addresses, UUIDs, and much more. The library is based on macros and traits, allowing you to easily combine validation rules and create custom checks.

Why is data validation needed?

In any application that works with user input, APIs, or configuration files, it is critically important to validate data before using it. Validation errors can lead to program crashes, vulnerabilities, or incorrect behavior. The validator library helps to:

  • Guarantee data integrity
  • Reduce the amount of boilerplate code
  • Ensure uniform error handling
  • Simplify testing

Installation

Add validator to the Cargo.toml file:

[dependencies]validator = "0.18"serde = { version = "1.0", features = ["derive"] }

serde is also often used for deserializing data before validation.

Main Features

  • Validation attributes — #[validate(...)] for struct fields
  • Built-in validators: length, range, email, url, ip, uuid, contains, regex, custom
  • Nested validation — recursive checking of nested structures
  • Custom validators — via functions or closures
  • Error grouping — collecting all validation errors into a single ValidationErrors object

Rust Code Example

use validator::Validate;use serde::Deserialize;

#[derive(Debug, Deserialize, Validate)]struct User { #[validate(length(min = 2, max = 50))] name: String,

#[validate(email)] email: String,

#[validate(range(min = 13, max = 120))] age: u8,

#[validate(url)] website: Option<String>,}

fn main() { let user = User { name: "A".to_string(), email: "invalid-email".to_string(), age: 10, website: Some("not-a-url".to_string()), };

match user.validate() { Ok(_) => println!("Data is valid"), Err(errors) => { for (field, errs) in errors.field_errors() { for err in errs { println!("Error in field {}: {}", field, err); } } } }}

When to use validator?

The library is ideal for:

  • Web servers using Actix, Axum, Rocket
  • Processing forms and JSON requests
  • Parsing configuration files
  • CLI applications with user input
  • Validating data before writing to a database

If you need to quickly and reliably validate data in Rust — validator is an excellent choice.

Recommendations