diff --git a/src/api/auth.rs b/src/api/auth.rs index 9c3956b..9e75f01 100644 --- a/src/api/auth.rs +++ b/src/api/auth.rs @@ -34,10 +34,14 @@ fn validate_username(username: &str) -> Result<(), String> { Ok(()) } +#[cfg(feature = "server")] +static EMAIL_REGEX: std::sync::LazyLock = std::sync::LazyLock::new(|| { + regex::Regex::new(r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$").unwrap() +}); + #[cfg(feature = "server")] fn validate_email(email: &str) -> Result<(), String> { - let re = regex::Regex::new(r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$").unwrap(); - if !re.is_match(email) { + if !EMAIL_REGEX.is_match(email) { return Err("邮箱格式不正确".to_string()); } Ok(()) diff --git a/src/api/comments/helpers.rs b/src/api/comments/helpers.rs index 297a0bb..fc3e548 100644 --- a/src/api/comments/helpers.rs +++ b/src/api/comments/helpers.rs @@ -109,11 +109,15 @@ pub fn validate_comment_name(name: &str) -> Result<(), String> { Ok(()) } +#[cfg(feature = "server")] +static EMAIL_REGEX: std::sync::LazyLock = std::sync::LazyLock::new(|| { + regex::Regex::new(r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$").unwrap() +}); + /// 校验评论作者邮箱格式。 #[cfg(feature = "server")] pub fn validate_comment_email(email: &str) -> Result<(), String> { - let re = regex::Regex::new(r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$").unwrap(); - if !re.is_match(email.trim()) { + if !EMAIL_REGEX.is_match(email.trim()) { return Err("邮箱格式不正确".to_string()); } Ok(())