Improve username validation

This commit is contained in:
silverpill 2022-02-17 20:15:30 +00:00
parent 82e24ad8b0
commit 0993a3b38c

View file

@ -1,10 +1,20 @@
use regex::Regex;
use crate::errors::ValidationError;
use crate::utils::html::{clean_html, clean_html_strict};
const USERNAME_RE: &str = r"^[a-zA-Z0-9_\.-]+$";
pub fn validate_username(username: &str) -> Result<(), ValidationError> {
if username.is_empty() {
return Err(ValidationError("username is empty"));
};
if username.len() > 100 {
return Err(ValidationError("username is too long"));
};
let username_regexp = Regex::new(USERNAME_RE).unwrap();
if !username_regexp.is_match(username) {
return Err(ValidationError("invalid username"));
};
Ok(())
}
@ -41,8 +51,18 @@ mod tests {
fn test_validate_username() {
let result_1 = validate_username("test");
assert!(result_1.is_ok());
let result_2 = validate_username(&"x".repeat(101));
assert!(result_2.is_err());
let result_2 = validate_username("test_12-3.xyz");
assert!(result_2.is_ok());
}
#[test]
fn test_validate_username_error() {
let error = validate_username(&"x".repeat(101)).unwrap_err();
assert_eq!(error.to_string(), "username is too long");
let error = validate_username("").unwrap_err();
assert_eq!(error.to_string(), "username is empty");
let error = validate_username("abc&").unwrap_err();
assert_eq!(error.to_string(), "invalid username");
}
#[test]