pub(crate) fn is_valid_hex(s: &str) -> bool {
!s.is_empty() && s.bytes().all(|b| b.is_ascii_hexdigit())
}
pub(crate) fn is_valid_credit_card(s: &str) -> bool {
if !s
.bytes()
.all(|b| b.is_ascii_digit() || b == b' ' || b == b'-')
{
return false;
}
let digits: Vec<u32> = s.chars().filter_map(|c| c.to_digit(10)).collect();
if digits.len() < 12 || digits.len() > 19 {
return false;
}
let sum: u32 = digits
.iter()
.rev()
.enumerate()
.map(|(i, &d)| match (i % 2 == 1, d * 2) {
(true, v) if v > 9 => v - 9,
(true, v) => v,
(false, _) => d,
})
.sum();
sum.is_multiple_of(10)
}
pub(crate) fn is_valid_phone(s: &str) -> bool {
let Some(rest) = s.strip_prefix('+') else {
return false;
};
if !rest
.bytes()
.all(|b| b.is_ascii_digit() || matches!(b, b' ' | b'-' | b'(' | b')'))
{
return false;
}
(8..=15).contains(&rest.bytes().filter(u8::is_ascii_digit).count())
}
#[cfg(feature = "string-advanced")]
pub(crate) fn is_valid_phone_e164_strict(s: &str) -> bool {
phonenumber::parse(None, s).is_ok_and(|n| phonenumber::is_valid(&n))
}
pub(crate) fn is_valid_slug(s: &str) -> bool {
!s.is_empty()
&& !s.starts_with('-')
&& !s.ends_with('-')
&& s.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
}
pub(crate) fn is_valid_color(s: &str) -> bool {
if let Some(hex) = s.strip_prefix('#') {
return (hex.len() == 6 || hex.len() == 8) && hex.bytes().all(|b| b.is_ascii_hexdigit());
}
let lower = s.to_ascii_lowercase();
let num = |p: &str| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit());
let parts_of = |prefix: &str| -> Option<Vec<String>> {
let inner = lower.strip_prefix(prefix)?.strip_suffix(')')?;
let parts: Vec<String> = inner.split(',').map(|p| p.trim().to_string()).collect();
(parts.len() == 3).then_some(parts)
};
if let Some(parts) = parts_of("rgb(") {
return parts.iter().all(|p| num(p) && p.parse::<u8>().is_ok());
}
if let Some(parts) = parts_of("hsl(") {
let pct = |p: &str| {
p.strip_suffix('%')
.filter(|v| num(v))
.and_then(|v| v.parse::<u8>().ok())
.is_some_and(|v| v <= 100)
};
return num(&parts[0])
&& parts[0].parse::<u16>().is_ok_and(|h| h <= 360)
&& pct(&parts[1])
&& pct(&parts[2]);
}
false
}
pub(crate) fn is_valid_currency_code(s: &str) -> bool {
crate::primitives::iso4217::is_currency(s)
}
pub(crate) fn is_valid_country_code(s: &str) -> bool {
s.len() == 2 && s.bytes().all(|b| b.is_ascii_uppercase())
}
pub(crate) fn is_valid_locale(s: &str) -> bool {
let b = s.as_bytes();
match b.len() {
2 => b.iter().all(u8::is_ascii_lowercase),
5 => {
b[2] == b'-'
&& b[..2].iter().all(u8::is_ascii_lowercase)
&& b[3..].iter().all(u8::is_ascii_uppercase)
}
_ => false,
}
}
pub(crate) fn is_valid_cron(s: &str) -> bool {
const MONTHS: [&str; 12] = [
"JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC",
];
const DAYS: [&str; 7] = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"];
if s.starts_with('@') {
return matches!(
s,
"@yearly" | "@annually" | "@monthly" | "@weekly" | "@daily" | "@midnight" | "@hourly"
);
}
let fields: Vec<&str> = s.split_whitespace().collect();
let spec = [
(0, 59, &[][..], false),
(0, 59, &[][..], false),
(0, 23, &[][..], false),
(1, 31, &[][..], true),
(1, 12, &MONTHS[..], false),
(0, 7, &DAYS[..], true),
];
let spec = match fields.len() {
5 => &spec[1..],
6 => &spec[..],
_ => return false,
};
fields
.iter()
.zip(spec)
.all(|(field, &(lo, hi, names, question))| {
let value = |v: &str| -> Option<u32> {
if !v.is_empty() && v.bytes().all(|b| b.is_ascii_digit()) {
return v.parse().ok().filter(|n| (lo..=hi).contains(n));
}
names
.iter()
.position(|n| n.eq_ignore_ascii_case(v))
.map(|i| lo + i as u32)
};
(question && *field == "?")
|| field.split(',').all(|item| {
let (base, step) = match item.split_once('/') {
Some((b, st)) => (b, Some(st)),
None => (item, None),
};
let step_ok = step.is_none_or(|st| {
!st.is_empty()
&& st.bytes().all(|b| b.is_ascii_digit())
&& st
.parse::<u32>()
.is_ok_and(|n| (1..=hi.max(1)).contains(&n))
});
let base_ok = base == "*"
|| match base.split_once('-') {
Some((a, b)) => {
matches!((value(a), value(b)), (Some(a), Some(b)) if a <= b)
}
None => value(base).is_some(),
};
step_ok && base_ok
})
})
}
fn is_mime_name(s: &str) -> bool {
(1..=127).contains(&s.len())
&& s.as_bytes()[0].is_ascii_alphanumeric()
&& s.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"!#$&-^_.+".contains(&b))
}
pub(crate) fn is_valid_mime(s: &str) -> bool {
let mut parts = s.split(';');
let essence = parts.next().unwrap_or("");
let Some((ty, sub)) = essence.split_once('/') else {
return false;
};
let tchar = |b: u8| b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b);
let quoted = |v: &str| {
let Some(inner) = v.strip_prefix('"').and_then(|v| v.strip_suffix('"')) else {
return false;
};
let mut escaped = false;
inner.chars().all(|c| {
let ok = escaped || c != '"';
escaped = !escaped && c == '\\';
ok && !c.is_control()
}) && !escaped
};
is_mime_name(ty)
&& is_mime_name(sub)
&& parts.all(|p| {
let Some((name, value)) = p.trim_start_matches([' ', '\t']).split_once('=') else {
return false;
};
is_mime_name(name) && (quoted(value) || (!value.is_empty() && value.bytes().all(tchar)))
})
}
pub(crate) fn is_valid_timezone(s: &str) -> bool {
#[cfg(feature = "jiff")]
{
is_timezone_shape(s)
&& jiff::tz::db()
.get(s)
.is_ok_and(|tz| tz.iana_name() == Some(s))
}
#[cfg(not(feature = "jiff"))]
{
is_timezone_shape(s)
}
}
fn is_timezone_shape(s: &str) -> bool {
let parts: Vec<&str> = s.split('/').collect();
s.len() <= 255
&& (1..=3).contains(&parts.len())
&& parts.iter().all(|p| {
p.as_bytes().first().is_some_and(u8::is_ascii_uppercase)
&& p.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'+'))
})
}
#[cfg(feature = "regex")]
pub(crate) fn is_valid_regex(s: &str) -> bool {
regex_lite::Regex::new(s).is_ok()
}
#[cfg(feature = "unicode")]
pub(crate) fn is_single_script(s: &str) -> bool {
use unicode_security::MixedScript;
s.is_single_script()
}
pub(crate) fn is_emoji_char(c: char) -> bool {
let cp = c as u32;
matches!(cp,
0x1F600..=0x1F64F
| 0x1F300..=0x1F5FF
| 0x1F680..=0x1F6FF
| 0x1F1E0..=0x1F1FF
| 0x2702..=0x27B0
| 0x2600..=0x26FF
| 0xFE00..=0xFE0F
| 0x1F900..=0x1F9FF
| 0x1FA00..=0x1FAFF
| 0x231A..=0x231B
| 0x23E9..=0x23F3
| 0x23F8..=0x23FA
| 0xE0020..=0xE007F | 0x20E3 | 0x200D
| 0x2B50)
}
fn is_emoji_modifier(c: char) -> bool {
matches!(c as u32, 0xFE00..=0xFE0F | 0x200D | 0x20E3 | 0xE0020..=0xE007F)
}
pub(crate) fn is_valid_emoji(s: &str) -> bool {
s.chars().all(is_emoji_char) && s.chars().any(|c| !is_emoji_modifier(c))
}