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_uuid(s: &str) -> bool {
let mut hex_count = 0u32;
for &b in s.as_bytes() {
if b == b'-' {
continue;
}
if !b.is_ascii_hexdigit() {
return false;
}
hex_count += 1;
}
hex_count == 32
}
pub fn is_domain(s: &str) -> bool {
if s.is_empty() || s.len() > 253 {
return false;
}
let parts: Vec<&str> = s.split('.').collect();
if parts.len() < 2 {
return false;
}
for part in &parts {
if part.is_empty() || part.len() > 63 {
return false;
}
if part.starts_with('-') || part.ends_with('-') {
return false;
}
if !part.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') {
return false;
}
}
let tld = parts.last().unwrap();
tld.len() >= 2 && tld.chars().all(|c| c.is_ascii_alphabetic())
}
pub fn is_port(s: &str) -> bool {
s.parse::<u16>()
.map(|p| p > 0)
.unwrap_or(false)
}
pub fn is_chinese(s: &str) -> bool {
!s.is_empty() && s.chars().all(|c| !c.is_ascii() && c.is_alphabetic())
}
pub fn is_json(s: &str) -> bool {
serde_json::from_str::<serde_json::Value>(s).is_ok()
}
pub fn is_enum(s: &str, values: &[&str]) -> bool {
values.contains(&s)
}
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"));
}
#[test]
fn test_is_uuid() {
assert!(Valid::is_uuid("550e8400-e29b-41d4-a716-446655440000"));
assert!(Valid::is_uuid("550e8400e29b41d4a716446655440000")); assert!(!Valid::is_uuid("not-a-uuid"));
assert!(!Valid::is_uuid("550e8400-e29b-41d4-a716")); }
#[test]
fn test_is_domain() {
assert!(Valid::is_domain("example.com"));
assert!(Valid::is_domain("sub.example.co.uk"));
assert!(!Valid::is_domain("localhost")); assert!(!Valid::is_domain(".com")); assert!(!Valid::is_domain("example.c")); }
#[test]
fn test_is_port() {
assert!(Valid::is_port("80"));
assert!(Valid::is_port("443"));
assert!(Valid::is_port("65535"));
assert!(!Valid::is_port("0"));
assert!(!Valid::is_port("65536"));
assert!(!Valid::is_port("abc"));
}
#[test]
fn test_is_chinese() {
assert!(Valid::is_chinese("中文"));
assert!(Valid::is_chinese("你好世界"));
assert!(!Valid::is_chinese("中文abc")); assert!(!Valid::is_chinese(""));
assert!(!Valid::is_chinese("123"));
}
#[test]
fn test_is_json() {
assert!(Valid::is_json("{\"key\": \"value\"}"));
assert!(Valid::is_json("[1, 2, 3]"));
assert!(Valid::is_json("\"string\""));
assert!(!Valid::is_json("{invalid}"));
assert!(!Valid::is_json(""));
}
#[test]
fn test_is_enum() {
assert!(Valid::is_enum("active", &["active", "inactive", "pending"]));
assert!(!Valid::is_enum("deleted", &["active", "inactive", "pending"]));
}
}