use regex::Regex;
use crate::error::{Error, Result};
pub struct ValidationUtils;
impl ValidationUtils {
pub fn validate_email(email: &str) -> Result<()> {
let re = Regex::new(r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$")
.map_err(|e| Error::System(e.to_string()))?;
if !re.is_match(email) {
return Err(Error::Validation("无效的邮箱地址".to_string()));
}
Ok(())
}
pub fn validate_phone(phone: &str) -> Result<()> {
let re = Regex::new(r"^1[3-9]\d{9}$").map_err(|e| Error::System(e.to_string()))?;
if !re.is_match(phone) {
return Err(Error::Validation("无效的手机号".to_string()));
}
Ok(())
}
pub fn validate_password(password: &str) -> Result<()> {
if password.len() < 8 {
return Err(Error::Validation("密码长度不能小于8位".to_string()));
}
let re =
Regex::new(r"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$")
.map_err(|e| Error::System(e.to_string()))?;
if !re.is_match(password) {
return Err(Error::Validation(
"密码必须包含大小写字母、数字和特殊字符".to_string(),
));
}
Ok(())
}
pub fn validate_url(url: &str) -> Result<()> {
let re =
Regex::new(r"^https?://[\w\-]+(\.[\w\-]+)+([\w\-.,@?^=%&:/~+#]*[\w\-@?^=%&/~+#])?$")
.map_err(|e| Error::System(e.to_string()))?;
if !re.is_match(url) {
return Err(Error::Validation("无效的URL".to_string()));
}
Ok(())
}
pub fn validate_ip(ip: &str) -> Result<()> {
let re = Regex::new(r"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$")
.map_err(|e| Error::System(e.to_string()))?;
if !re.is_match(ip) {
return Err(Error::Validation("无效的IP地址".to_string()));
}
Ok(())
}
pub fn validate_id_card(id: &str) -> Result<()> {
let re = Regex::new(
r"^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])\d{3}[\dXx]$",
)
.map_err(|e| Error::System(e.to_string()))?;
if !re.is_match(id) {
return Err(Error::Validation("无效的身份证号".to_string()));
}
Ok(())
}
}
#[macro_export]
macro_rules! validate_field {
($field:expr, $validator:expr) => {
if let Err(e) = $validator($field) {
return Err(e);
}
};
}
#[macro_export]
macro_rules! validate_object {
($obj:expr) => {
if let Err(e) = $obj.validate() {
return Err(Error::Validation(e.to_string()));
}
};
}