1 /*
2  * Hunt - A data validation for DLang based on hunt library.
3  *
4  * Copyright (C) 2015-2019, HuntLabs
5  *
6  * Website: https://www.huntlabs.net
7  *
8  * Licensed under the Apache-2.0 License.
9  *
10  */
11 module hunt.validation.validators.EmailValidator;
12 
13 import hunt.validation.constraints.Email;
14 import hunt.validation.ConstraintValidator;
15 import hunt.validation.ConstraintValidatorContext;
16 import hunt.validation.util.DomainNameUtil;
17 import hunt.validation.Validator;
18 
19 import hunt.logging;
20 import std.regex;
21 import std.string;
22 
23 public class EmailValidator : AbstractValidator , ConstraintValidator!(Email, string) {
24 
25     static const string ATOM = "[a-z0-9!#$%&'*+/=?^_`{|}~-]";
26     static const string DOMAIN = "(" ~ ATOM ~ "+(\\." ~ ATOM ~ "+)+";
27     static const string IP_DOMAIN = "\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\]";
28 
29     static const string PATTERN =
30             "^" ~ ATOM ~ "+(\\." ~ ATOM ~ "+)*@"
31                     ~ DOMAIN
32                     ~ "|"
33                     ~ IP_DOMAIN
34                     ~ ")$";
35     private  Email _email;
36 
37     override void initialize(Email constraintAnnotation) {
38         _email = constraintAnnotation;
39     }
40     
41     override
42     public bool isValid(string data, ConstraintValidatorContext constraintValidatorContext) {
43         scope(exit) constraintValidatorContext.append(this);    
44 
45         auto splitPosition = data.indexOf( '@' );
46 
47         // need to check if
48         if ( splitPosition < 0 ) {
49             _isValid = false;
50             return false;
51         }
52 
53         // string localPart = data[0 .. splitPosition];
54         // string domainPart = data[splitPosition+1 .. $];
55 
56         // if ( !isValidEmailLocalPart( localPart ) ) {
57         //     return false;
58         // }
59 
60         // return DomainNameUtil.isValidEmailDomainAddress( domainPart );
61         _isValid = isValidEmail(data);
62 
63         return _isValid;
64     }
65 
66     private bool isValidEmailLocalPart(string localPart) {
67         auto matcher = matchAll(localPart, regex("^" ~ ATOM ~ "+(\\." ~ ATOM ~ "+)*"));
68         return !matcher.empty();
69     }
70 
71     private bool isValidEmail(string email) {
72         auto matcher = matchAll(email, regex( _email.pattern.length == 0 ? PATTERN : _email.pattern));
73         return !matcher.empty();
74     }
75 
76     override string getMessage()
77     {
78         return _email.message;
79     }
80 }