rust的nutyp驗證和validator驗證數(shù)據(jù)的方法示例詳解
更新時間:2024年09月29日 11:10:49 作者:jr-create(?????)
本文介紹了在Rust語言中,如何使用nuType和validator兩種工具來對Cargo.toml和modules.rs文件進(jìn)行驗證,通過具體的代碼示例和操作步驟,詳細(xì)解釋了驗證過程和相關(guān)配置,幫助讀者更好地理解和掌握使用這兩種驗證工具的方法,更多Rust相關(guān)技術(shù)資訊,可繼續(xù)關(guān)注腳本之家
使用nutype驗證
Cargo.toml
nutype = { version = "0.5.0", features = ["serde","regex"] }
regex = "1"
thiserror = "1"modules.rs
#[nutype(
sanitize(trim, lowercase),
validate(not_empty, len_char_min = 3, len_char_max = 30),
derive(AsRef, Clone, Debug, Serialize, Deserialize, PartialEq)
)]
// AsRef表示可以單獨(dú)訪問username,clone復(fù)制
pub struct Username(String);
// #[nutype(
// validate(not_empty, len_char_min = 8),
// derive(AsRef, Clone, Serialize, Deserialize, PartialEq)
// )]
#[nutype(validate(with = password_regex, error = ErrorMessage),derive(Debug, PartialEq),)]
pub struct Password(String);
// 正則匹配手機(jī)號
static PHONE_NUMBER_REGEX: LazyLock<Regex> = LazyLock::new(||
Regex::new("^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\\d{8}$"
).unwrap());
// 直接使用正則表達(dá)式
#[nutype(validate(regex = PHONE_NUMBER_REGEX))]
pub struct PhoneNumber(String);
// 自定義方法
#[nutype(validate(with = email_regex, error = ErrorMessage))]
pub struct EmailNumber(String);
// 正則匹配郵箱號
static EMAIL_NUMBER_REGEX: LazyLock<Regex> = LazyLock::new(||
Regex::new("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$"
).unwrap());
pub fn email_regex(name: &str) -> Result<(), ErrorMessage> {
match EMAIL_NUMBER_REGEX.captures(name){
// 這里可以返回自定義的錯誤類型
None => Err(ErrorMessage::InvalidEmailFormat),
Some(_) => Ok(())
}
}使用validator驗證
Cargo.toml
validator = {version = "0.18.1",features = ["derive"]}
lazy_static = "1.5.0"modules.rs
#[derive(Validate, Debug, Default, Clone, Serialize, Deserialize)]
pub struct RegisterUserDto {
#[validate(length(min = 1, message = "姓名為必填項"))]
pub name: String,
#[validate(length(min = 0, message = "用戶名不是必填項"))]
pub username: String,
#[validate(
length(min = 1, message = "電子郵件是必需的"),
email(message = "電子郵件無效")
)]
pub email: String,
#[validate(
length(min = 1, message = "手機(jī)號是必需的"),
)]
pub phone: String,
#[validate(
length(min = 6, message = "密碼必須至少為 6 個字符")
)]
pub password: String,
#[validate(
length(min = 1, message = "需要確認(rèn)密碼"),
must_match(other = "password", message="密碼不匹配")
)]
#[serde(rename = "passwordConfirm")]
pub password_confirm: String,
}
//validator自定義方法是無法使用自定義錯誤類型的,必須使用crate的,具體看validator crate到此這篇關(guān)于rust的nutyp驗證和validator驗證數(shù)據(jù)的方法的文章就介紹到這了,更多相關(guān)rust nutyp驗證和validator驗證數(shù)據(jù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Rust使用Sqlx連接Mysql的實(shí)現(xiàn)
數(shù)據(jù)庫在編程中是一個很重要的環(huán)節(jié),本文主要介紹了Rust使用Sqlx連接Mysql的實(shí)現(xiàn),記錄rust如何操作數(shù)據(jù)庫并以mysql為主的做簡單的使用說明,感興趣的可以了解一下2024-03-03
rust的nutyp驗證和validator驗證數(shù)據(jù)的方法示例詳解
本文介紹了在Rust語言中,如何使用nuType和validator兩種工具來對Cargo.toml和modules.rs文件進(jìn)行驗證,通過具體的代碼示例和操作步驟,詳細(xì)解釋了驗證過程和相關(guān)配置,幫助讀者更好地理解和掌握使用這兩種驗證工具的方法,更多Rust相關(guān)技術(shù)資訊,可繼續(xù)關(guān)注腳本之家2024-09-09

