Skip to main content

this_me/utils/
validate_input.rs

1
2use std::io;
3
4pub fn validate_username(username: &str) -> io::Result<()> {
5    println!("🔍 Validating username: '{}' (chars: {}, bytes: {})", username, username.chars().count(), username.len());
6
7    let username_len = username.len();
8    if username_len < 5 || username_len > 21 {
9        return Err(io::Error::new(io::ErrorKind::InvalidInput, "❌ Username must be 5-21 characters long."));
10    }
11
12    if username.starts_with('.') || username.starts_with('_') {
13        return Err(io::Error::new(io::ErrorKind::InvalidInput, "❌ Username cannot start with '.' or '_'"));
14    }
15
16    if username.ends_with('.') || username.ends_with('_') {
17        return Err(io::Error::new(io::ErrorKind::InvalidInput, "❌ Username cannot end with '.' or '_'"));
18    }
19
20    if username.contains("..") || username.contains("__") || username.contains("._") || username.contains("_.") {
21        return Err(io::Error::new(io::ErrorKind::InvalidInput, "❌ Username cannot contain consecutive '.' or '_'"));
22    }
23
24    if !username.chars().all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '_') {
25        return Err(io::Error::new(io::ErrorKind::InvalidInput, "❌ Username must only contain letters, numbers, '.' or '_'"));
26    }
27
28    let period_count = username.matches('.').count();
29    if period_count > 2 {
30        return Err(io::Error::new(io::ErrorKind::InvalidInput, "❌ Username cannot have more than 2 periods."));
31    }
32
33    Ok(())
34}
35pub fn validate_password(password: &str) -> io::Result<()> {
36    if password.len() < 4 {
37        return Err(io::Error::new(io::ErrorKind::InvalidInput, "❌ Password must be at least 4 characters long."));
38    }
39    Ok(())
40}