Files
server/src/Core/Utilities/StrictEmailAddressAttribute.cs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

51 lines
1.5 KiB
C#
Raw Normal View History

using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;
using MimeKit;
namespace Bit.Core.Utilities;
2022-08-29 16:06:55 -04:00
public class StrictEmailAddressAttribute : ValidationAttribute
{
public StrictEmailAddressAttribute()
: base("The {0} field is not a supported e-mail address format.")
{ }
public override bool IsValid(object value)
2022-08-29 16:06:55 -04:00
{
var emailAddress = value?.ToString();
if (emailAddress == null)
2022-08-29 14:53:16 -04:00
{
return false;
}
2022-08-29 14:53:16 -04:00
try
2022-08-29 16:06:55 -04:00
{
var parsedEmailAddress = MailboxAddress.Parse(emailAddress).Address;
if (parsedEmailAddress != emailAddress)
{
return false;
}
2022-08-29 16:06:55 -04:00
}
catch (ParseException)
2022-08-29 16:06:55 -04:00
{
return false;
2022-08-29 16:06:55 -04:00
}
// The regex below is intended to catch edge cases that are not handled by the general parsing check above.
// This enforces the following rules:
// * Requires ASCII only in the local-part (code points 0-127)
// * Requires an @ symbol
// * Allows any char in second-level domain name, including unicode and symbols
// * Requires at least one period (.) separating SLD from TLD
// * Must end in a letter (including unicode)
// See the unit tests for examples of what is allowed.
var emailFormat = @"^[\x00-\x7F]+@.+\.\p{L}+$";
if (!Regex.IsMatch(emailAddress, emailFormat))
2022-08-29 16:06:55 -04:00
{
return false;
}
2022-08-29 16:06:55 -04:00
return new EmailAddressAttribute().IsValid(emailAddress);
}
}