ForkScalewayScalewaypublished Aug 18, 2025seen 5d

scaleway/validator

forked from Keats/validator

Open original ↗

Captured source

source ↗
published Aug 18, 2025seen 5dcaptured 18hhttp 200method plain

scaleway/validator

Description: Simple validation for Rust structs

License: MIT

Stars: 0

Forks: 0

Open issues: 0

Created: 2025-08-18T09:42:55Z

Pushed: 2025-08-18T09:46:03Z

Default branch: master

Fork: yes

Parent repository: Keats/validator

Archived: no

README:

validator

Macros 1.1 custom derive to simplify struct validation inspired by marshmallow and Django validators.

Installation:

[dependencies]
validator = { version = "0.19", features = ["derive"] }

A short example:

use serde::Deserialize;

// A trait that the Validate derive will impl
use validator::{Validate, ValidationError};

#[derive(Debug, Validate, Deserialize)]
struct SignupData {
#[validate(email)]
mail: String,
#[validate(url)]
site: String,
#[validate(length(min = 1), custom(function = "validate_unique_username"))]
#[serde(rename = "firstName")]
first_name: String,
#[validate(range(min = 18, max = 20))]
age: u32,
#[validate(range(exclusive_min = 0.0, max = 100.0))]
height: f32,
}

fn validate_unique_username(username: &str) -> Result {
if username == "xXxShad0wxXx" {
// the value of the username will automatically be added later
return Err(ValidationError::new("terrible_username"));
}

Ok(())
}

match signup_data.validate() {
Ok(_) => (),
Err(e) => return e;
};

A validation on an Option field will be executed on the contained type if the option is Some. The validate() method returns a Result. In the case of an invalid result, the ValidationErrors instance includes a map of errors keyed against the struct's field names. Errors may be represented in three ways, as described by the ValidationErrorsKind enum:

#[derive(Debug, Serialize, Clone, PartialEq)]
#[serde(untagged)]
pub enum ValidationErrorsKind {
Struct(Box),
List(BTreeMap>),
Field(Vec),
}

In the simple example above, any errors would be of the Field(Vec) type, where a single ValidationError has the following structure:

#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub struct ValidationError {
pub code: Cow,
pub message: Option>,
pub params: HashMap, Value>,
}

The value of the field will automatically be added to the params with a key of value.

The other two ValidationErrorsKind types represent errors discovered in nested (vectors of) structs, as described in this example:

use serde::Deserialize;
// A trait that the Validate derive will impl
use validator::Validate;

#[derive(Debug, Validate, Deserialize)]
struct SignupData {
#[validate(nested)]
contact_details: ContactDetails,
#[validate(nested)]
preferences: Vec,
#[validate(required)]
allow_cookies: Option,
}

#[derive(Debug, Validate, Deserialize)]
struct ContactDetails {
#[validate(email)]
mail: String,
}

#[derive(Debug, Validate, Deserialize)]
struct Preference {
#[validate(length(min = 4))]
name: String,
value: bool,
}

match signup_data.validate() {
Ok(_) => (),
Err(e) => return e;
};

Here, the ContactDetails and Preference structs are nested within the parent SignupData struct. Because these child types also derive Validate, the fields where they appear can be tagged for inclusion in the parent struct's validation method.

Any errors found in a single nested struct (the contact_details field in this example) would be returned as a Struct(Box) type in the parent's ValidationErrors result.

Any errors found in a vector of nested structs (the preferences field in this example) would be returned as a List(BTreeMap>) type in the parent's ValidationErrors result, where the map is keyed on the index of invalid vector entries.

Usage

You will need to import the Validate trait.

The validator crate can also be used without the custom derive as it exposes all the validation functions and types.

Validators

The crate comes with some built-in validators and you can have several validators for a given field.

email

Tests whether the String is a valid email according to the HTML5 regex, which means it will mark some esoteric emails as invalid that won't be valid in a email input as well. This validator doesn't take any arguments: #[validate(email)].

url

Tests whether the String is a valid URL. This validator doesn't take any arguments: #[validate(url)];

length

Tests whether a String or a Vec match the length requirement given. length has 3 integer arguments:

  • min
  • max
  • equal

Using equal excludes the min or max and will result in a compilation error if they are found.

At least one argument is required with a maximum of 2 (having min and max at the same time).

Examples:

const MIN_CONST: u64 = 1;
const MAX_CONST: u64 = 10;

#[validate(length(min = 1, max = 10))]
#[validate(length(min = 1))]
#[validate(length(max = 10))]
#[validate(length(equal = 10))]
#[validate(length(min = "MIN_CONST", max = "MAX_CONST"))]

range

Tests whether a number is in the given range. range takes 1 or 2 arguments, and they can be normal (min and max) or exclusive (exclusive_min, exclusive_max, unreachable limits). These can be a number or a value path.

Examples:

const MAX_CONSTANT: i32 = 10;
const MIN_CONSTANT: i32 = 0;

#[validate(range(min = 1))]
#[validate(range(min = "MIN_CONSTANT"))]
#[validate(range(min = 1, max = 10))]
#[validate(range(min = 1.1, max = 10.8))]
#[validate(range(max = 10.8))]
#[validate(range(min = "MAX_CONSTANT"))]
#[validate(range(min = "crate::MAX_CONSTANT"))]
#[validate(range(exclusive_min = 0.0, max = 100.0))]
#[validate(range(exclusive_max = 10))]
// If you get an error saying the literal doesn't fit in i32, specify a number type in the literal directly
#[validate(range(max = 1000000000u64))]

must_match

Tests whether the 2 fields are equal. must_match takes 1 string argument. It will error if the field mentioned is missing or has a different type than the field the attribute is on.

Examples:

#[validate(must_match(other = "password2"))]

contains

Tests whether the string contains the substring given or if a key is present in a hashmap. contains takes 1 string argument.

Examples:

#[validate(contains = "gmail")]
#[validate(contains(pattern = "gmail"))]

does_not_contain

Pretty much the opposite of contains, provided just for ease-of-use. Tests whether a container does not contain the substring given if it's a string or if a key is NOT...

Excerpt shown — open the source for the full document.

Notability

notability 1.0/10

Routine fork by a cloud provider