Read-only mirrors. Development, issues and pull requests are on GitHub.

summaryrefslogtreecommitdiffhomepage
path: root/apps/api/Accounts/EmailAddressPolicy.cs
blob: 9710b0c5e38d6a6b61ade100fba4eb45b8a1ac61 (plain)
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
// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com>
// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1

using System.Net.Mail;

namespace Progmasoft.Progmaweb.Api.Accounts;

internal static class EmailAddressPolicy
{
    public const int MaximumLength = 254;

    public static bool TryNormalize(string? value, out string canonical, out string normalized, out string error)
    {
        canonical = value?.Trim() ?? string.Empty;
        normalized = string.Empty;

        if (canonical.Length is 0 or > MaximumLength)
        {
            error = "Enter a valid email address.";
            return false;
        }

        try
        {
            MailAddress parsed = new(canonical);
            if (!string.Equals(parsed.Address, canonical, StringComparison.OrdinalIgnoreCase))
            {
                error = "Enter a single email address without a display name.";
                return false;
            }
        }
        catch (FormatException)
        {
            error = "Enter a valid email address.";
            return false;
        }

        normalized = canonical.ToUpperInvariant();
        error = string.Empty;
        return true;
    }
}