Rust - validator 结构体字段验证

一、添加 validator 依赖库

validator 是基于过程宏的方式注入

[dependencies]
validator = "0.10.0"
validator_derive = "0.10.0"
serde = "1.0.105"
serde_json = "1.0.50"
serde_derive = "1.0.105"
二、使用示例

1、注入过程宏

#[macro_use]
extern crate validator_derive;
extern crate validator;

use serde_derive::{Deserialize};
use validator::{Validate, ValidationErrors};

#[derive(Debug, Validate, Deserialize)]
struct RegisterForm {
    #[validate(length(max = 10, message="username must be less than 10 chars."))]
    username: Option<String>,
    #[validate(length(min = 6, message="password must be more than 6 chars."))]
    password: Option<String>,
    #[validate(length(equal = 4, message="captcha is 4 chars."))]
    captcha: Option<String>,
    #[validate(custom(function="valid_custom_fn", message="invlaid identity"))]
    identity: Option<String>,
}

fn valid_custom_fn(value: &str) -> Result<(), ValidationError> {
    if value != "123123" {
        return Err(ValidationError::new("invalid identity"))
    }
    Ok(())
}

2、解析json格式请求参数

    let put = r#"{"username": "daojianshenjun", "password": "5678", "captcha": "12345", "identity": "111"}"#;
    let p: RegisterForm = serde_json::from_str(put).unwrap();

3、校验结构体规则

    if let Err(e) = p.validate() {
        println!("{:?}", e);
    }

三、过程宏的规则列表

规则名 描述
length(min, max, equal) 判断字符串的长度
range(min, max) 判断数字的范围
email 邮箱
url url
phone 手机号码,需要开启feature【phone】
credit_card 信用卡,需要开启feature【card】
custom(function) 自定义校验规则的函数名,如valid_custom_fn
contains(pattern) 字符串必须包含有pattern
must_match(other) 当前字段必须和另一个字段一模一样
regex(path) 正则表达式,path必须为当前作用域有效的静态变量,正则字符串
nested 嵌套验证,直接注解不需要参数,#[validate]
non_control_character unicode 字符集
schema(function,skip_on_field_errors) 校验结构体struct
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章