1 个不稳定版本
0.1.0 | 2023年3月11日 |
---|
#256 在 #structs
844 每月下载次数
用于 not-so-fast
52KB
930 行(不包括注释)
not-so-fast
一个用于数据验证的 Rust 库。
特性
- 用于报告验证错误的 Builder 模式 API
- 易于组合验证器
- 为结构体和枚举实现验证特质的派生宏
- 使用类似于 jq 的路径显示错误
- 反映输入数据结构的错误序列化
安装
cargo add not-so-fast # --features derive serde
可用的 cargo 功能
derive
- 启用Validate
派生宏,默认禁用serde
- 启用serde::Serialize
对ValidationNode
的实现,默认禁用
使用方法
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()
);
指南
not-so-fast/examples/manual.rs 解释了如何编写自定义验证器。
not-so-fast/examples/derive.rs 展示了如何使用验证器派生宏。
与 validator 对比
not-so-fast
尝试修复我在使用流行的 https://github.com/Keats/validator crate 时遇到的问题。两个库的 API 类似,但不兼容。以下是 not-so-fast
的不同之处:
- 验证器组合 - 在
not-so-fast
中组合验证器很简单,因为所有值 - 数字、字符串、对象、列表 - 都使用相同的类型 -ValidationNode
- 报告验证错误。 - 基本验证器 -
not-so-fast
仅包含基本验证器。您需要编写自定义验证器以测试数据是否符合您领域规则。 - 枚举支持 -
Validate
派生宏与结构体和枚举一起工作。 - 鸭子类型 -
Validate
派生宏完全不考虑字段类型。为了验证容器内的数据,您需要向派生宏提供如何访问数据的提示(some
、items
、fields
属性)。作为回报,not-so-fast
将能够与具有类似std API的第三方容器类型一起工作。
待办事项
- 添加
matches
派生验证器,用于测试字符串与正则表达式是否匹配 - 添加
is_some
/required
派生验证器,用于测试选项 - 考虑将派生验证器从
not-so-fast-derive
移动到not-so-fast
以提高代码的可重用性
许可
根据您的选择,在Apache License,Version 2.0或MIT许可证下许可。
除非您明确声明,否则根据Apache-2.0许可证定义,您有意提交给本软件包的任何贡献都应双重许可如上所述,没有任何附加条款或条件。
依赖关系
~1.5MB
~34K SLoC