Skip to content

Commit bcf31e0

Browse files
committed
...
1 parent 42ac180 commit bcf31e0

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

src/rule/string.rs

+2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
11
mod alphabet;
2+
mod email;
23

34
pub use alphabet::{Alphabet, AlphabetRule};
5+
pub use email::{Email, EmailRule};

src/rule/string/email.rs

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
use crate::result::Error;
2+
use crate::rule::Rule;
3+
use crate::Refined;
4+
use regex::Regex;
5+
6+
pub type Email = Refined<EmailRule>;
7+
8+
pub struct EmailRule;
9+
10+
impl Rule for EmailRule {
11+
type Item = String;
12+
13+
fn validate(target: Self::Item) -> Result<Self::Item, Error<Self::Item>> {
14+
let regex =
15+
Regex::new(r"^[a-zA-Z0-9_.+-]+@([a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]*\.)+[a-zA-Z]{2,}$")
16+
.unwrap();
17+
if regex.is_match(&target) {
18+
Ok(target)
19+
} else {
20+
Err(Error::new(
21+
format!("{target} is not a valid email format"),
22+
target,
23+
))
24+
}
25+
}
26+
}
27+
28+
#[cfg(test)]
29+
mod test {
30+
use crate::rule::string::email::EmailRule;
31+
use crate::rule::Rule;
32+
33+
#[test]
34+
fn test_valid_email() {
35+
let valid = "[email protected]".to_string();
36+
assert!(EmailRule::validate(valid).is_ok())
37+
}
38+
39+
#[test]
40+
fn test_invalid_email_1() {
41+
let invalid = "example.com".to_string();
42+
assert!(EmailRule::validate(invalid).is_err())
43+
}
44+
45+
#[test]
46+
fn test_invalid_email_2() {
47+
let invalid = "@".to_string();
48+
assert!(EmailRule::validate(invalid).is_err())
49+
}
50+
}

0 commit comments

Comments
 (0)