-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEmail.cs
More file actions
56 lines (45 loc) · 1.67 KB
/
Email.cs
File metadata and controls
56 lines (45 loc) · 1.67 KB
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
using System.Text.RegularExpressions;
namespace ValueObjects.Network
{
public class Email : ValueObject
{
public string Address { get; private set; }
public string User { get; private set; }
public string Host { get; private set; }
private Email(string email)
{
Ensure.Argument.NotNullOrEmpty(email, nameof(email));
Ensure.Argument.Is(IsValidEmail(email), $"The email address '{email}' is invalid.");
var parts = email.Split('@');
Address = email;
User = parts[0];
Host = parts[1];
}
public static Email FromAddress(string email)
{
return new Email(email);
}
/// <see cref="https://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx/"/>
private static bool IsValidEmail(string email)
{
string pattern = @"^(?!\.)(""([^""\r\\]|\\[""\r\\])*""|"
+ @"([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\.)\.)*)(?<!\.)"
+ @"@[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$";
var regex = new Regex(pattern, RegexOptions.IgnoreCase);
var isValid = regex.IsMatch(email);
return isValid;
}
protected override IEnumerable<object> GetAtomicValues()
{
yield return Address.ToLower();
}
public static implicit operator string(Email email)
{
return email.Address;
}
public static explicit operator Email(string email)
{
return new Email(email);
}
}
}