2021-07-23 05:59:10 +10:00
|
|
|
|
using System.ComponentModel.DataAnnotations;
|
2021-08-10 12:16:10 -04:00
|
|
|
|
using System.Text.RegularExpressions;
|
2021-07-23 05:59:10 +10:00
|
|
|
|
using MimeKit;
|
2021-07-16 08:01:51 +10:00
|
|
|
|
|
|
|
|
|
|
namespace Bit.Core.Utilities;
|
2022-08-29 16:06:55 -04:00
|
|
|
|
|
2021-07-16 08:01:51 +10:00
|
|
|
|
public class StrictEmailAddressAttribute : ValidationAttribute
|
|
|
|
|
|
{
|
|
|
|
|
|
public StrictEmailAddressAttribute()
|
|
|
|
|
|
: base("The {0} field is not a supported e-mail address format.")
|
2021-07-23 05:59:10 +10:00
|
|
|
|
{ }
|
2021-08-10 12:16:10 -04:00
|
|
|
|
|
2021-07-16 08:01:51 +10:00
|
|
|
|
public override bool IsValid(object value)
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2021-08-31 13:49:11 +10:00
|
|
|
|
var emailAddress = value?.ToString();
|
|
|
|
|
|
if (emailAddress == null)
|
2022-08-29 14:53:16 -04:00
|
|
|
|
{
|
2021-07-16 08:01:51 +10:00
|
|
|
|
return false;
|
2022-08-29 15:53:48 -04:00
|
|
|
|
}
|
2022-08-29 14:53:16 -04:00
|
|
|
|
|
2021-07-16 08:01:51 +10:00
|
|
|
|
try
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2021-07-16 08:01:51 +10:00
|
|
|
|
var parsedEmailAddress = MailboxAddress.Parse(emailAddress).Address;
|
|
|
|
|
|
if (parsedEmailAddress != emailAddress)
|
2022-08-29 15:53:48 -04:00
|
|
|
|
{
|
2021-08-10 12:16:10 -04:00
|
|
|
|
return false;
|
2022-08-29 15:53:48 -04:00
|
|
|
|
}
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
2021-07-16 08:01:51 +10:00
|
|
|
|
catch (ParseException)
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2021-07-16 08:01:51 +10:00
|
|
|
|
return false;
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
2022-08-29 15:53:48 -04:00
|
|
|
|
|
2022-10-18 22:12:26 +02: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.
|
2021-07-23 05:59:10 +10:00
|
|
|
|
var emailFormat = @"^[\x00-\x7F]+@.+\.\p{L}+$";
|
|
|
|
|
|
if (!Regex.IsMatch(emailAddress, emailFormat))
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2021-07-23 05:59:10 +10:00
|
|
|
|
return false;
|
2022-08-29 15:53:48 -04:00
|
|
|
|
}
|
2022-08-29 16:06:55 -04:00
|
|
|
|
|
2021-07-16 08:01:51 +10:00
|
|
|
|
return new EmailAddressAttribute().IsValid(emailAddress);
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|