SoFunction
Updated on 2025-03-02

Detailed explanation of the examples of rust's nuclear verification and validator's method of validator's verification of data

Verification with Nutype

nutype = { version = "0.5.0", features = ["serde","regex"] }
regex = "1"
thiserror = "1"

#[nutype(
sanitize(trim, lowercase),
validate(not_empty, len_char_min = 3, len_char_max = 30),
derive(AsRef, Clone, Debug, Serialize, Deserialize, PartialEq)
)]
// AsRef means that username can be accessed separately and clone copypub 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);
// Regularly match mobile phone numberstatic 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());
// Use regular expressions directly#[nutype(validate(regex = PHONE_NUMBER_REGEX))]
pub struct PhoneNumber(String);
// Custom method#[nutype(validate(with = email_regex, error = ErrorMessage))]
pub struct EmailNumber(String);
// Regularly match email numberstatic 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){
		// Here you can return a custom error type		None => Err(ErrorMessage::InvalidEmailFormat),
		Some(_) => Ok(())
	}
}

Verification with validator

validator = {version = "0.18.1",features = ["derive"]}
lazy_static = "1.5.0"

#[derive(Validate, Debug, Default, Clone, Serialize, Deserialize)]
pub struct RegisterUserDto {
#[validate(length(min = 1, message = "Name is required"))]pub name: String,
#[validate(length(min = 0, message = "User name is not required"))]pub username: String,
#[validate(
length(min = 1, message = "Email is required"),
email(message = "Invalid email")
)]
pub email: String,
#[validate(
length(min = 1, message = "Mobile phone number is required"),
)]
pub phone: String,
#[validate(
length(min = 6, message = "The password must be at least 6 characters")
)]
pub password: String,
#[validate(
length(min = 1, message = "Requires a password"),
must_match(other = "password", message="Password mismatch")
)]
#[serde(rename = "passwordConfirm")]
pub password_confirm: String,
}
//validatorCustom methods cannot use custom error types,Must usecrateof,See morevalidator crate

This is the article about rust's nuclear verification and validator data verification methods. For more related rust nuclear verification and validator data content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!