File tree 2 files changed +52
-0
lines changed
2 files changed +52
-0
lines changed Original file line number Diff line number Diff line change 1
1
mod alphabet;
2
+ mod email;
2
3
3
4
pub use alphabet:: { Alphabet , AlphabetRule } ;
5
+ pub use email:: { Email , EmailRule } ;
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments