Crate valitron

source ·
Expand description

Valitron is an ergonomics, functional and configurable validator.

§This is an example:

#[derive(Serialize, Debug)]
struct Person {
    introduce: &'static str,
    age: u8,
    weight: f32,
}

let validator = Validator::new()
    .rule("introduce", Required.and(StartWith("I am")))
    .rule("age", custom(age_range))
    .message([
        ("introduce.required", "introduce is required"),
        (
            "introduce.start_with",
            "introduce should be starts with `I am`",
        ),
    ]);

let person = Person {
    introduce: "hi",
    age: 18,
    weight: 20.0,
};

let res = validator.validate(person).unwrap_err();
assert!(res.len() == 2);

fn age_range(age: &mut u8) -> Result<(), Message> {
    if *age >= 25 && *age <= 45 {
        Ok(())
    } else {
        Err("age should be between 25 and 45".into())
    }
}

The second scheme is string.

§Prerequisite

input data needs implementation serde::Serialize, and if you want to modify data, it should be also implementation serde::Deserialize

§Available Rules

To get started using all of Valitron’s optional rule, add this to your Cargo.toml:

valitron = { version = "0.1", features = ["full"] }

§Closure Rule

This is support closure with a primitive type mutable reference arguments and returning message type.

§Tip

message type is Validator’s only one generics argument, default is String, but when full features enabled default is Message, and it is customable. And it’s not immutable, it can be changed by map method.

§Custom Rule

anything types implemented Rule trait can be used as a rule

Re-exports§

Modules§

  • register validator
  • define Rule trait, and build-in rule types
  • define Value, ValueMap types