rust的nutyp验证和validator验证数据的方法
使用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表示可以单独访问username,clone复制
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);
// 正则匹配手机号
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());
// 直接使用正则表达式
#[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 = "手机号是必需的"),
)]
pub phone: String,
#[validate(
length(min = 6, message = "密码必须至少为 6 个字符")
)]
pub password: String,
#[validate(
length(min = 1, message = "需要确认密码"),
must_match(other = "password", message="密码不匹配")
)]
#[serde(rename = "passwordConfirm")]
pub password_confirm: String,
}
//validator自定义方法是无法使用自定义错误类型的,必须使用crate的,具体看validator crate