#input-validation #validation #ergonomics #serde

valitron

Valitron is an ergonomics, functional and configurable validator

12 releases (4 breaking)

new 0.5.0 May 17, 2024
0.4.1 May 12, 2024
0.4.0 Apr 19, 2024
0.3.0 Nov 9, 2023
0.0.1 Aug 26, 2023

#390 in Encoding

Download history 2/week @ 2024-02-22 2/week @ 2024-02-29 3/week @ 2024-03-07 15/week @ 2024-03-14 22/week @ 2024-03-28 11/week @ 2024-04-04 10/week @ 2024-04-11 309/week @ 2024-04-18 7/week @ 2024-04-25 139/week @ 2024-05-09

464 downloads per month

MIT/Apache

200KB
5.5K SLoC

Valitron is an ergonomics, functional and configurable validation

In the future, modularization will be supported

Inspired by axum

Features

  • Ergonomics validation
  • Build-in rule, e.g. Required, StartWith ...
  • Closure validate
  • Related validate, e.g. password confirm
  • Custom rule with other parameter
  • Check / modify input data
  • Custom error message type
  • Support different error types convert, it can use both build-in rules and custom error type simultaneously
  • Collect validate error messages
  • Support all types data on #[derive(Serialize, Deserialize)] ( visit serde for more info)

Examples

fn main() {
    let validator = Validator::new()
        .rule("name", Required.and(StartWith("hello")))
        .rule("age", custom(age_limit))
        .message([
            ("name.required", "name is required"),
            ("name.start_with", "name should be starts with `hello`"),
        ]);

    let person = Person {
        name: "li",
        age: 18,
    };

    let res = validator.validate(person);
    // or using trait
    let res = person.validate(validator);
}

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

Rules Usage

Usage Description
Required one rule
Required.and(StartsWith("foo")) multi rules
Required.and(StartsWith('a')).bail() multi rules and bail
custom(my_handler) custom handler rule
Required.custom(my_handler) rule and handler rule
Not(StartsWith("foo")) negative rule
Required.and(Not(StartsWith("foo"))) negative rule

License

Licensed under either of Apache License, Version 2.0 or MIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Dependencies

~0.1–1.1MB
~25K SLoC