What is validator?
validator is a popular library for data validation in Rust, providing a simple and expressive way to check the correctness of input data. It is based on macros and annotations, allowing you to describe validation rules directly in data structures. The library supports checks such as string length, number range, regular expressions, required fields, and custom validators.
Why is validation needed?
In any application that works with external data (user input, API requests, configuration files), it is critically important to check the correctness of this data before processing it. Validation errors can lead to program crashes, security vulnerabilities, or incorrect logic. validator allows you to centrally describe rules, automatically generate clear error messages, and avoid boilerplate code.
Installation
Add to Cargo.toml:
[dependencies]validator = { version = "0.16", features = ["derive"] }serde = { version = "1.0", features = ["derive"] }It is also often used together with serde for data deserialization.
Main Features
- Validation attributes:
#[validate(length(min = 1, max = 100))],#[validate(range(min = 18, max = 99))],#[validate(email)],#[validate(regex = "...")]and others. - Custom validators: via the attribute
#[validate(custom = "my_function")]. - Nested validation: for structures containing other structures.
- Error grouping: returns
ValidationErrorswith details per field.
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 = 18, max = 120))] age: u8,
#[validate(required)] #[validate(length(min = 8))] password: Option<String>,}
fn main() { let user = User { name: "A".to_string(), // too short email: "invalid".to_string(), age: 15, password: Some("123".to_string()), };
match user.validate() { Ok(_) => println!("Data is valid"), Err(errors) => { for (field, err_list) in errors.field_errors() { println!("Field '{}' has errors:", field); for err in err_list { println!(" - {}", err.message.as_ref().unwrap_or(&"unknown error".to_string())); } } } }}When to use validator?
- When creating REST APIs (e.g., with Actix-web, Axum, Rocket) to validate incoming JSON requests.
- In CLI applications for validating command-line arguments.
- When processing forms on the server side.
- Anywhere declarative data validation with minimal code is required.
The library is ideal for projects where security and code readability are important. It is actively maintained and widely used in the Rust ecosystem.
Also in library
Symfony/Validator for PHP: Complete Guide with Examples
Generating PDF Reports in Go: Library Overview and Code Examples
Internationalization (i18n) in JavaScript (Node.js): i18next Library