Crate not_so_fast

source ·
Expand description

A library for validating arbitrary data with simple API and a derive macro.

Example

use not_so_fast::{Validate, ValidationNode, ValidationError};

#[derive(Validate)]
struct User {
    #[validate(custom = alpha_only, char_length(max = 30))]
    nick: String,
    #[validate(range(min = 15, max = 100))]
    age: u8,
    #[validate(length(max = 3), items(char_length(max = 50)))]
    cars: Vec<String>,
}

fn alpha_only(s: &str) -> ValidationNode {
    ValidationNode::error_if(
        s.chars().any(|c| !c.is_alphanumeric()),
        || ValidationError::with_code("alpha_only")
    )
}

let user = User {
    nick: "**tom1980**".into(),
    age: 200,
    cars: vec![
        "first".into(),
        "second".into(),
        "third".repeat(11),
        "fourth".into(),
    ],
};

let node = user.validate();
assert!(node.is_err());
assert_eq!(
    vec![
        ".age: range: Number not in range: max=100, min=15, value=200",
        ".cars: length: Invalid length: max=3, value=4",
        ".cars[2]: char_length: Invalid character length: max=50, value=55",
        ".nick: alpha_only",
    ].join("\n"),
    node.to_string()
);

Structs

  • Describes what is wrong with the validated value. It contains code, an optional message, and a list of error parameters.
  • Container for ValidationErrors associated with some value. If the value is an object or a list, field or item ValidationNodes can be attached to the root node, effectively forming an error tree.

Enums

Traits

  • Trait describing types that can be validated without arguments. It is automatically implemented for all types that implement ValidateArgs<Args=()>.
  • Trait describing types that can be validated with arguments.