| | | 1 | | using System.Text.RegularExpressions; |
| | | 2 | | using Enjoy.Domain.Shared.Errors; |
| | | 3 | | using Enjoy.Domain.Shared.Extensions; |
| | | 4 | | using Enjoy.Domain.Shared.Results; |
| | | 5 | | |
| | | 6 | | namespace Enjoy.Domain.Users.ValueObjects; |
| | | 7 | | |
| | | 8 | | public readonly record struct Email |
| | | 9 | | { |
| | 7 | 10 | | public string Value { get; } |
| | | 11 | | |
| | | 12 | | public const int MinLength = 8; |
| | | 13 | | public const int MaxLength = 50; |
| | | 14 | | |
| | | 15 | | public const string EmailPattern = @"^[^@]+@[^@]+$"; |
| | | 16 | | |
| | 60 | 17 | | private Email(string value) => Value = value; |
| | | 18 | | |
| | | 19 | | public static Result<Email> Create(string value) |
| | 73 | 20 | | { |
| | 73 | 21 | | if (string.IsNullOrWhiteSpace(value)) |
| | 7 | 22 | | return Result<Email>.Failure(Error.Email.IsNullOrEmpty); |
| | | 23 | | |
| | 66 | 24 | | var normalized = value.Trim().ToLowerInvariant(); |
| | 66 | 25 | | List<Error> errors = []; |
| | 66 | 26 | | if (normalized.Length < MinLength) |
| | 2 | 27 | | errors.Add(Error.Email.TooShort(MinLength)); |
| | 66 | 28 | | if (normalized.Length > MaxLength) |
| | 1 | 29 | | errors.Add(Error.Email.TooLong(MaxLength)); |
| | 66 | 30 | | if (!Regex.IsMatch(normalized, EmailPattern)) |
| | 4 | 31 | | errors.Add(Error.Email.InvalidFormat); |
| | | 32 | | |
| | 66 | 33 | | return errors.IsEmpty() |
| | 66 | 34 | | ? Result<Email>.Success(new Email(normalized)) |
| | 66 | 35 | | : Result<Email>.Failure(errors); |
| | 73 | 36 | | } |
| | | 37 | | |
| | 1 | 38 | | public override string ToString() => Value; |
| | | 39 | | |
| | 1 | 40 | | public static implicit operator string(Email email) => email.Value; |
| | | 41 | | } |