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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章