mirror of
https://github.com/storytold/artcraft.git
synced 2026-11-17 07:04:36 +00:00
44 lines
1.1 KiB
Rust
44 lines
1.1 KiB
Rust
use regex::Regex;
|
|
|
|
pub fn validate_username(username: &str) -> Result<(), String> {
|
|
lazy_static! {
|
|
static ref USERNAME_REGEX: Regex = {
|
|
Regex::new(r"^[A-Za-z0-9_\-]{3,16}$").expect("should be valid regex")
|
|
};
|
|
}
|
|
|
|
if username.len() < 3 {
|
|
return Err("username is too short".to_string());
|
|
}
|
|
|
|
if username.len() > 16 {
|
|
return Err("username is too long".to_string());
|
|
}
|
|
|
|
if !USERNAME_REGEX.is_match(username) {
|
|
return Err("invalid username characters".to_string());
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use crate::validations::validate_username::validate_username;
|
|
|
|
#[test]
|
|
fn test_valid_usernames() {
|
|
assert!(validate_username("echelon").is_ok());
|
|
assert!(validate_username("dr_mario").is_ok());
|
|
assert!(validate_username("Foo1234").is_ok());
|
|
assert!(validate_username("mr-person").is_ok());
|
|
}
|
|
|
|
#[test]
|
|
fn test_invalid_usernames() {
|
|
assert!(validate_username("").is_err());
|
|
assert!(validate_username("&&&&").is_err());
|
|
assert!(validate_username("........").is_err());
|
|
assert!(validate_username("really-long-username-that-is-too-long").is_err());
|
|
}
|
|
} |