在Rust中,你可以通過以下方法加強驗證:
validator
或serde_with
來對結構體進行驗證。這些庫允許你為結構體的字段添加約束,例如必填字段、長度限制等。首先,將依賴項添加到Cargo.toml
文件中:
[dependencies]
validator = "0.13.0"
serde_with = "1.0.0"
然后,在結構體上使用#[validator]
屬性添加驗證規則:
use validator::Validate;
#[derive(Debug, Validate)]
struct User {
#[validate(length(min = 1, max = 100))]
username: String,
#[validate(length(min = 6, max = 20))]
password: String,
}
最后,使用validator::validate
函數驗證結構體:
fn main() {
let user = User {
username: "JohnDoe".to_string(),
password: "password123".to_string(),
};
if let Err(errors) = user.validate() {
eprintln!("Validation errors: {:?}", errors);
} else {
println!("Validation passed");
}
}
fn is_valid_email(email: &str) -> bool {
regex::Regex::new(r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$").unwrap().is_match(email)
}
fn main() {
let email = "john.doe@example.com";
if is_valid_email(email) {
println!("Valid email");
} else {
println!("Invalid email");
}
}
fn is_valid_age(age: u32) -> bool {
age >= 18 && age <= 120
}
fn main() {
let age = 25;
if is_valid_age(age) {
println!("Valid age");
} else {
println!("Invalid age");
}
}
通過這些方法,你可以在Rust中加強驗證,確保數據的有效性和安全性。