it编程 > 编程语言 > rust

rust的nutyp验证和validator验证数据的方法示例详解

299人参与 2024-09-29 rust

使用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

到此这篇关于rust的nutyp验证和validator验证数据的方法的文章就介绍到这了,更多相关rust nutyp验证和validator验证数据内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)
打赏 微信扫一扫 微信扫一扫

您想发表意见!!点此发布评论

推荐阅读

详解Rust调用tree-sitter支持自定义语言解析

09-26

如何使用Rust直接编译单个的Solidity合约

09-20

Rust整合Elasticsearch的详细过程(收藏)

11-02

MySQL中的log_bin_trust_function_creators系统变量

09-02

Rust调用Windows API 如何获取正在运行的全部进程信息

11-19

Rust 数据分析利器polars用法详解

08-20

猜你喜欢

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论