IsEmailAttribute.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using Masuit.Tools.Core.Config;
  2. using System.ComponentModel.DataAnnotations;
  3. using System.Linq;
  4. namespace Masuit.Tools.Core.Validator
  5. {
  6. /// <summary>
  7. /// 邮箱校验
  8. /// </summary>
  9. public class IsEmailAttribute : ValidationAttribute
  10. {
  11. private readonly bool _valid;
  12. /// <summary>
  13. /// 域白名单
  14. /// </summary>
  15. private string DomainWhiteList { get; }
  16. /// <summary>
  17. /// 可在配置文件AppSetting节中添加EmailDomainWhiteList配置邮箱域名白名单,逗号分隔
  18. /// </summary>
  19. /// <param name="valid">是否检查邮箱的有效性</param>
  20. public IsEmailAttribute(bool valid = true)
  21. {
  22. DomainWhiteList = ConfigHelper.GetConfigOrDefault("EmailDomainWhiteList", string.Empty);
  23. _valid = valid;
  24. }
  25. /// <summary>
  26. /// 邮箱校验
  27. /// </summary>
  28. /// <param name="value"></param>
  29. /// <returns></returns>
  30. public override bool IsValid(object value)
  31. {
  32. if (value == null)
  33. {
  34. ErrorMessage = "邮箱不能为空!";
  35. return false;
  36. }
  37. var email = value as string;
  38. if (email.Length < 7)
  39. {
  40. ErrorMessage = "您输入的邮箱格式不正确!";
  41. return false;
  42. }
  43. if (email.Length > 256)
  44. {
  45. ErrorMessage = "邮箱长度最大允许255个字符!";
  46. return false;
  47. }
  48. if (DomainWhiteList.Split(',').Any(item => email.EndsWith("@" + item)))
  49. {
  50. return true;
  51. }
  52. if (email.MatchEmail(_valid).isMatch)
  53. {
  54. return true;
  55. }
  56. ErrorMessage = "您输入的邮箱格式不正确!";
  57. return false;
  58. }
  59. }
  60. }