自己这两天边学边写,搞了个简单的验证器过程宏,
用在 web 框架里面可以比较方便的验证前端传来的各个字段
github 地址:https://github.com/horou-dsk/fields-valid.git
刚学过程宏,写的很简陋,内置的功能不多
有大佬觉得写的不好的话,还望指点迷津
示例:
use fields_valid::FieldsValidate;
#[derive(FieldsValidate)]
struct User {
// #[valid(len(5, 11), email, regex("^[\\d@\\.]+$"), "邮箱格式不正确")]
#[valid(len(5, 17), "The length of the mailbox must be between 5-16")]
#[valid(email, "E-mail format is incorrect")]
email: String,
#[valid(len(8, 17), "The minimum password length is 8 digits and the maximum is 16 digits")]
password: String,
#[valid(eq("#password"), "The two passwords are inconsistent")]
password2: String,
#[valid(len(5, 12), "The length of the phone number is incorrect")]
#[valid(regex("\\d+"), "The phone number must be a number")]
phone: Option<String>,
#[valid(range(5.8, 10.1), "Incorrect amount returned")]
amount: u32,
}
#[inline]
fn fields_validate<T: FieldsValidate>(fields: &T) -> Result<(), &'static str> {
fields.fields_validate()
}
fn main() {
let user = User {
email: "111@11a.com".to_string(),
password: "12ndd232.23".to_string(),
password2: "1225".to_string(),
phone: None, //Some("111111".to_string())
amount: 7,
};
println!("{:?}", fields_validate(&user));
}
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.