baichun_framework_core/
validation.rs1use regex::Regex;
2
3use crate::error::{Error, Result};
4
5pub struct ValidationUtils;
7
8impl ValidationUtils {
9 pub fn validate_email(email: &str) -> Result<()> {
11 let re = Regex::new(r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$")
12 .map_err(|e| Error::System(e.to_string()))?;
13 if !re.is_match(email) {
14 return Err(Error::Validation("无效的邮箱地址".to_string()));
15 }
16 Ok(())
17 }
18
19 pub fn validate_phone(phone: &str) -> Result<()> {
21 let re = Regex::new(r"^1[3-9]\d{9}$").map_err(|e| Error::System(e.to_string()))?;
22 if !re.is_match(phone) {
23 return Err(Error::Validation("无效的手机号".to_string()));
24 }
25 Ok(())
26 }
27
28 pub fn validate_password(password: &str) -> Result<()> {
30 if password.len() < 8 {
31 return Err(Error::Validation("密码长度不能小于8位".to_string()));
32 }
33 let re =
34 Regex::new(r"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$")
35 .map_err(|e| Error::System(e.to_string()))?;
36 if !re.is_match(password) {
37 return Err(Error::Validation(
38 "密码必须包含大小写字母、数字和特殊字符".to_string(),
39 ));
40 }
41 Ok(())
42 }
43
44 pub fn validate_url(url: &str) -> Result<()> {
46 let re =
47 Regex::new(r"^https?://[\w\-]+(\.[\w\-]+)+([\w\-.,@?^=%&:/~+#]*[\w\-@?^=%&/~+#])?$")
48 .map_err(|e| Error::System(e.to_string()))?;
49 if !re.is_match(url) {
50 return Err(Error::Validation("无效的URL".to_string()));
51 }
52 Ok(())
53 }
54
55 pub fn validate_ip(ip: &str) -> Result<()> {
57 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]?)$")
58 .map_err(|e| Error::System(e.to_string()))?;
59 if !re.is_match(ip) {
60 return Err(Error::Validation("无效的IP地址".to_string()));
61 }
62 Ok(())
63 }
64
65 pub fn validate_id_card(id: &str) -> Result<()> {
67 let re = Regex::new(
68 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]$",
69 )
70 .map_err(|e| Error::System(e.to_string()))?;
71 if !re.is_match(id) {
72 return Err(Error::Validation("无效的身份证号".to_string()));
73 }
74 Ok(())
75 }
76}
77
78#[macro_export]
80macro_rules! validate_field {
81 ($field:expr, $validator:expr) => {
82 if let Err(e) = $validator($field) {
83 return Err(e);
84 }
85 };
86}
87
88#[macro_export]
90macro_rules! validate_object {
91 ($obj:expr) => {
92 if let Err(e) = $obj.validate() {
93 return Err(Error::Validation(e.to_string()));
94 }
95 };
96}