1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
use crate::Error::{BadFormat, Unexpected}; use regex::Regex; use thiserror::Error; #[derive(Error, Debug)] pub enum Error { #[error("invalid format: {0}")] BadFormat(String), #[error("unexpected error ({0})")] Unexpected(String), } pub fn validate_format(email: impl Into<String>) -> Result<(), Error> { let re = Regex::new(r"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$") .map_err(|e| Unexpected(e.to_string()))?; let email_string = email.into(); let ok = re.is_match(&email_string); if !ok { return Err(BadFormat(email_string)); } Ok(()) } #[cfg(test)] mod tests { use super::*; struct Sample { mail: String, format: bool, account: bool, } fn setup() -> Vec<Sample> { vec![ Sample { mail: "florian@carrere.cc".to_string(), format: true, account: true, }, Sample { mail: "support@g2mail.com".to_string(), format: true, account: false, }, Sample { mail: "florian@carrere.cc ".to_string(), format: false, account: false, }, Sample { mail: "test@912-wrong-domain902.com".to_string(), format: true, account: false, }, Sample { mail: "0932910-qsdcqozuioqkdmqpeidj8793@gmail.com".to_string(), format: true, account: false, }, Sample { mail: " florian@carrere.cc".to_string(), format: false, account: false, }, Sample { mail: "@gmail.com".to_string(), format: false, account: false, }, Sample { mail: "test@gmail@gmail.com".to_string(), format: false, account: false, }, Sample { mail: "test test@gmail.com".to_string(), format: false, account: false, }, Sample { mail: " test@gmail.com".to_string(), format: false, account: false, }, Sample { mail: "test@wrong domain.com".to_string(), format: false, account: false, }, Sample { mail: "é&ààà@gmail.com".to_string(), format: false, account: false, }, Sample { mail: "admin@busyboo.com".to_string(), format: true, account: false, }, Sample { mail: "a@gmail.fi".to_string(), format: true, account: false, }, ] } #[test] fn test_validate_format() { let samples = setup(); for s in samples.iter() { let res = validate_format(&s.mail); if s.format { res.expect(format!("expected valid mail: {}", &s.mail).as_str()); } else { match res { Ok(_) => { panic!(format!("expected invalid mail: {}", &s.mail)); } Err(e) => { assert_eq!(e.to_string(), format!("invalid format: {}", &s.mail)); } } } } } }