1 个不稳定版本

0.0.0 2020年10月22日

#51 in #fluent

MIT 许可协议

16KB
138

瓦莱

vale on crates.io stripe-rust on docs.rs

瓦莱代表有效实体,是一个简单的库,通过注解或Fluent风格实现实体验证。库的核心是 vale::Validate 特性,这意味着可以验证数据片段。库还支持 rocket 网页框架。如果您有兴趣添加其他框架的支持,请毫不犹豫地提交一个PR!

示例

此示例展示了如何派生验证特性

use vale::Validate;

#[derive(Validate)]
struct Entity {
    #[validate(gt(0))]
    id: i32,
    #[validate(len_lt(5), with(add_element))]
    others: Vec<i32>,
    #[validate(eq("hello world"))]
    msg: String,
}

fn add_element(v: &mut Vec<i32>) -> bool {
    v.push(3);
    true
}

fn main() {
    let mut e = get_entity();
    if let Err(errs) = e.validate() {
        println!("The following validations failed: {:?}", errs);
    }
}

还可以使用Fluent风格的验证

struct Entity {
    id: i32,
    others: Vec<i32>,
    msg: String,
}

impl vale::Validate for Entity {
    #[vale::ruleset]
    fn validate(&mut self) -> vale::Result {
        vale::rule!(self.id > 0, "`id` is nonpositive!");
        vale::rule!(self.others.len() < 5, "Too many others");
    }
}

依赖项

~1.2–3MB
~65K SLoC