pub struct Valid;
impl Valid {
pub fn is_email(s: &str) -> bool {
if s.is_empty() || s.len() > 254 {
return false;
}
let Some(at) = s.rfind('@') else {
return false;
};
if at == 0 || at == s.len() - 1 {
return false;
}
let (local, domain) = (&s[..at], &s[at + 1..]);
let local_ok = !local.starts_with('.')
&& !local.ends_with('.')
&& !local.contains("..")
&& local
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '%' | '+' | '-'));
if !local_ok {
return false;
}
let Some(dot) = domain.rfind('.') else {
return false;
};
if dot == 0 || dot == domain.len() - 1 {
return false;
}
let tld = &domain[dot + 1..];
tld.len() >= 2
&& tld.chars().all(|c| c.is_ascii_alphabetic())
&& domain
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-')
}
pub fn is_mobile(s: &str) -> bool {
s.len() == 11
&& s.starts_with('1')
&& s.as_bytes()
.get(1)
.is_some_and(|b| (b'3'..=b'9').contains(b))
&& s.bytes().all(|b| b.is_ascii_digit())
}
pub fn is_url(s: &str) -> bool {
let Some(rest) = s
.strip_prefix("http://")
.or_else(|| s.strip_prefix("https://"))
else {
return false;
};
let Some(first) = rest.chars().next() else {
return false;
};
!"/.$?#".contains(first)
&& !first.is_whitespace()
&& rest.chars().all(|c| !c.is_whitespace())
}
pub fn is_digits(s: &str) -> bool {
!s.is_empty() && s.chars().all(|c| c.is_ascii_digit())
}
pub fn is_alphanumeric(s: &str) -> bool {
!s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric())
}
pub fn len_between(s: &str, min: usize, max: usize) -> bool {
let len = s.chars().count();
len >= min && len <= max
}
pub fn is_strong_password(s: &str) -> bool {
if s.len() < 8 {
return false;
}
let has_lower = s.chars().any(|c| c.is_ascii_lowercase());
let has_upper = s.chars().any(|c| c.is_ascii_uppercase());
let has_digit = s.chars().any(|c| c.is_ascii_digit());
has_lower && has_upper && has_digit
}
pub fn is_ipv4(s: &str) -> bool {
s.parse::<std::net::Ipv4Addr>().is_ok()
}
pub fn is_base64(s: &str) -> bool {
crate::Crypto::decode_base64(s).is_some()
}
pub fn is_empty(s: &str) -> bool {
s.trim().is_empty()
}
#[cfg(feature = "validator-integration")]
pub fn not_empty(s: &str, field_name: &str) -> Result<(), wordval_core::api::ApiError> {
if Self::is_empty(s) {
Err(wordval_core::api::ApiError::bad_request(format!(
"{}不能为空",
field_name
)))
} else {
Ok(())
}
}
#[cfg(feature = "validator-integration")]
#[track_caller]
pub fn must(
condition: bool,
msg: impl std::fmt::Display,
) -> Result<(), wordval_core::api::ApiError> {
if condition {
Ok(())
} else {
Err(wordval_core::api::ApiError::bad_request(msg.to_string()))
}
}
#[cfg(feature = "validator-integration")]
#[track_caller]
pub fn required<T>(
value: Option<T>,
msg: impl Into<std::borrow::Cow<'static, str>>,
) -> Result<T, wordval_core::api::ApiError> {
match value {
Some(v) => Ok(v),
None => Err(wordval_core::api::ApiError::bad_request(msg)),
}
}
#[cfg(feature = "validator-integration")]
pub fn lt(
actual: u64,
max: u64,
msg: impl std::fmt::Display,
) -> Result<(), wordval_core::api::ApiError> {
if actual < max {
Ok(())
} else {
Err(wordval_core::api::ApiError::bad_request(msg.to_string()))
}
}
#[cfg(feature = "validator-integration")]
pub fn slug(s: &str, field_name: &str) -> Result<(), wordval_core::api::ApiError> {
let ok = !s.is_empty()
&& s.len() <= 64
&& s.chars()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
&& !s.starts_with('-')
&& !s.ends_with('-');
if ok {
Ok(())
} else {
Err(wordval_core::api::ApiError::bad_request(format!(
"{}只能包含小写字母、数字和中划线,不能以中划线开头或结尾",
field_name
)))
}
}
}
#[cfg(feature = "validator-integration")]
impl Valid {
pub fn format_validation_errors(errors: &validator::ValidationErrors) -> String {
let mut messages = Vec::new();
for (field, field_errors) in errors.field_errors() {
for error in field_errors {
if let Some(msg) = &error.message {
messages.push(format!("{}: {}", field, msg));
} else {
messages.push(format!("{}: {}", field, error.code));
}
}
}
messages.join("; ")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_email() {
assert!(Valid::is_email("a@b.com"));
assert!(!Valid::is_email("not-email"));
}
#[test]
fn test_mobile() {
assert!(Valid::is_mobile("13812345678"));
assert!(!Valid::is_mobile("1234"));
}
#[test]
fn test_password() {
assert!(Valid::is_strong_password("Abcdefg1"));
assert!(!Valid::is_strong_password("123456"));
}
}